echarts to display the datafusion SQL

This commit is contained in:
Priec
2026-07-16 00:14:07 +02:00
parent b513dc0813
commit 53c7576872
6 changed files with 1168 additions and 0 deletions

1
graphs/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target/

761
graphs/Cargo.lock generated Normal file
View File

@@ -0,0 +1,761 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "analytics-graphs"
version = "0.1.0"
dependencies = [
"axum",
"prost",
"prost-types",
"serde",
"serde_json",
"tokio",
"tonic",
"tonic-prost",
]
[[package]]
name = "anyhow"
version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
[[package]]
name = "async-trait"
version = "0.1.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"bytes",
"form_urlencoded",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"serde_core",
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "either"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-channel"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-core"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-sink"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
[[package]]
name = "futures-task"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-util"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "h2"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155"
dependencies = [
"atomic-waker",
"bytes",
"fnv",
"futures-core",
"futures-sink",
"http",
"indexmap",
"slab",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "http"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "http-body"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "http-body-util"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"pin-project-lite",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hyper"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"
dependencies = [
"atomic-waker",
"bytes",
"futures-channel",
"futures-core",
"h2",
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
"tokio",
"want",
]
[[package]]
name = "hyper-timeout"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"
dependencies = [
"hyper",
"hyper-util",
"pin-project-lite",
"tokio",
"tower-service",
]
[[package]]
name = "hyper-util"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"hyper",
"libc",
"pin-project-lite",
"socket2",
"tokio",
"tower-service",
"tracing",
]
[[package]]
name = "indexmap"
version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "libc"
version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "log"
version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mio"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project"
version = "1.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
dependencies = [
"pin-project-internal",
]
[[package]]
name = "pin-project-internal"
version = "1.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "prost"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-derive"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
dependencies = [
"anyhow",
"itertools",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "prost-types"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
dependencies = [
"prost",
]
[[package]]
name = "quote"
version = "1.0.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
dependencies = [
"proc-macro2",
]
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
dependencies = [
"itoa",
"serde",
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
[[package]]
name = "socket2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
[[package]]
name = "tokio"
version = "1.52.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
dependencies = [
"bytes",
"libc",
"mio",
"pin-project-lite",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-stream"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
]
[[package]]
name = "tonic"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
dependencies = [
"async-trait",
"axum",
"base64",
"bytes",
"h2",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-timeout",
"hyper-util",
"percent-encoding",
"pin-project",
"socket2",
"sync_wrapper",
"tokio",
"tokio-stream",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tonic-prost"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"
dependencies = [
"bytes",
"prost",
"tonic",
]
[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"indexmap",
"pin-project-lite",
"slab",
"sync_wrapper",
"tokio",
"tokio-util",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"log",
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "try-lock"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "want"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
dependencies = [
"try-lock",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

16
graphs/Cargo.toml Normal file
View File

@@ -0,0 +1,16 @@
[package]
name = "analytics-graphs"
version = "0.1.0"
edition = "2024"
[workspace]
[dependencies]
axum = "0.8"
prost = "0.14.4"
prost-types = "0.14.4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] }
tonic = "0.14.6"
tonic-prost = "0.14.6"

28
graphs/README.md Normal file
View File

@@ -0,0 +1,28 @@
# Analytics graphs
A small Rust web server that forwards SQL queries to `AnalyticsService.ExecuteAnalyticsQuery`
and displays the streamed result with ECharts.
## Run
Start the main komp_ac gRPC server, then run:
```sh
cargo run
```
Open <http://127.0.0.1:3000>. The default gRPC endpoint is
`http://[::1]:50051`. Both addresses can be changed:
```sh
ANALYTICS_GRPC_ENDPOINT=http://127.0.0.1:50051 \
LISTEN_ADDRESS=127.0.0.1:8080 \
cargo run
```
The first SQL result column is used for category labels. Bar and line charts use
all remaining columns as numeric series, pie uses the second column, and scatter
uses the first two columns. Table view displays every returned value.
ECharts is loaded from jsDelivr, so the browser needs network access when opening
the page.

195
graphs/src/main.rs Normal file
View File

@@ -0,0 +1,195 @@
use std::{env, net::SocketAddr};
use axum::{
Json, Router,
extract::State,
http::StatusCode,
response::Html,
routing::{get, post},
};
mod analytics {
include!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../common/src/proto/komp_ac.analytics.rs"
));
}
use analytics::{
AnalyticsResultColumn, AnalyticsValue, ExecuteAnalyticsQueryRequest,
analytics_service_client::AnalyticsServiceClient, analytics_value,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tonic::{Request, metadata::MetadataValue, transport::Channel};
const INDEX_HTML: &str = include_str!("../static/index.html");
#[derive(Clone)]
struct AppState {
analytics: AnalyticsServiceClient<Channel>,
}
#[derive(Deserialize)]
struct QueryInput {
profile_name: String,
sql: String,
#[serde(default)]
token: String,
#[serde(default = "default_max_rows")]
max_rows: u32,
}
fn default_max_rows() -> u32 {
1_000
}
#[derive(Serialize)]
struct QueryOutput {
columns: Vec<ColumnOutput>,
rows: Vec<Vec<Value>>,
row_count: u64,
elapsed_ms: u64,
truncated: bool,
}
#[derive(Serialize)]
struct ColumnOutput {
name: String,
data_type: String,
}
#[derive(Serialize)]
struct ErrorOutput {
error: String,
}
type ApiResult<T> = Result<Json<T>, (StatusCode, Json<ErrorOutput>)>;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let grpc_endpoint =
env::var("ANALYTICS_GRPC_ENDPOINT").unwrap_or_else(|_| "http://[::1]:50051".into());
let listen_address = env::var("LISTEN_ADDRESS")
.unwrap_or_else(|_| "127.0.0.1:3000".into())
.parse::<SocketAddr>()?;
let channel = Channel::from_shared(grpc_endpoint.clone())?.connect_lazy();
let state = AppState {
analytics: AnalyticsServiceClient::new(channel),
};
let app = Router::new()
.route("/", get(index))
.route("/api/query", post(run_query))
.with_state(state);
let listener = tokio::net::TcpListener::bind(listen_address).await?;
println!("Analytics graphs: http://{listen_address}");
println!("Analytics gRPC endpoint: {grpc_endpoint}");
axum::serve(listener, app).await?;
Ok(())
}
async fn index() -> Html<&'static str> {
Html(INDEX_HTML)
}
async fn run_query(State(state): State<AppState>, Json(input): Json<QueryInput>) -> ApiResult<QueryOutput> {
if input.profile_name.trim().is_empty() || input.sql.trim().is_empty() {
return Err(api_error(
StatusCode::BAD_REQUEST,
"Profile name and SQL are required",
));
}
let mut request = Request::new(ExecuteAnalyticsQueryRequest {
profile_name: input.profile_name,
sql: input.sql,
max_rows: input.max_rows,
});
if !input.token.trim().is_empty() {
let value = MetadataValue::try_from(format!("Bearer {}", input.token.trim()))
.map_err(|_| api_error(StatusCode::BAD_REQUEST, "The bearer token is invalid"))?;
request.metadata_mut().insert("authorization", value);
}
let mut client = state.analytics;
let mut stream = client
.execute_analytics_query(request)
.await
.map_err(grpc_error)?
.into_inner();
let mut columns = Vec::new();
let mut rows = Vec::new();
let mut row_count = 0;
let mut elapsed_ms = 0;
let mut truncated = false;
while let Some(batch) = stream.message().await.map_err(grpc_error)? {
if !batch.columns.is_empty() {
columns = batch.columns.into_iter().map(column_output).collect();
}
rows.extend(batch.rows.into_iter().map(|row| {
row.values.into_iter().map(value_output).collect::<Vec<_>>()
}));
if batch.is_final {
row_count = batch.row_count;
elapsed_ms = batch.elapsed_ms;
truncated = batch.truncated;
}
}
Ok(Json(QueryOutput {
columns,
rows,
row_count,
elapsed_ms,
truncated,
}))
}
fn column_output(column: AnalyticsResultColumn) -> ColumnOutput {
ColumnOutput {
name: column.name,
data_type: column.data_type,
}
}
fn value_output(value: AnalyticsValue) -> Value {
match value.kind {
None | Some(analytics_value::Kind::NullValue(_)) => Value::Null,
Some(analytics_value::Kind::BoolValue(value)) => json!(value),
Some(analytics_value::Kind::Int64Value(value)) => json!(value),
Some(analytics_value::Kind::Uint64Value(value)) => json!(value),
Some(analytics_value::Kind::DoubleValue(value)) => json!(value),
Some(analytics_value::Kind::StringValue(value)) => json!(value),
Some(analytics_value::Kind::BytesValue(value)) => {
Value::String(value.iter().map(|byte| format!("{byte:02x}")).collect())
}
}
}
fn grpc_error(error: tonic::Status) -> (StatusCode, Json<ErrorOutput>) {
let status = match error.code() {
tonic::Code::InvalidArgument => StatusCode::BAD_REQUEST,
tonic::Code::Unauthenticated => StatusCode::UNAUTHORIZED,
tonic::Code::PermissionDenied => StatusCode::FORBIDDEN,
tonic::Code::NotFound => StatusCode::NOT_FOUND,
tonic::Code::ResourceExhausted => StatusCode::TOO_MANY_REQUESTS,
tonic::Code::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
_ => StatusCode::BAD_GATEWAY,
};
api_error(status, error.message())
}
fn api_error(status: StatusCode, message: impl Into<String>) -> (StatusCode, Json<ErrorOutput>) {
(
status,
Json(ErrorOutput {
error: message.into(),
}),
)
}

167
graphs/static/index.html Normal file
View File

@@ -0,0 +1,167 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Analytics graphs</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@6/dist/echarts.min.js"></script>
<style>
* { box-sizing: border-box; }
body { margin: 0; font: 14px system-ui, sans-serif; color: #17202a; background: #f4f6f8; }
main { width: min(1200px, calc(100% - 32px)); margin: 24px auto; }
h1 { margin: 0 0 18px; font-size: 24px; }
.panel { padding: 18px; border: 1px solid #dfe4ea; border-radius: 10px; background: white; }
.row { display: grid; grid-template-columns: 1fr 1fr 180px 120px; gap: 12px; margin-bottom: 12px; }
label { display: grid; gap: 5px; color: #4b5563; font-size: 12px; }
input, select, textarea, button { font: inherit; }
input, select, textarea { width: 100%; border: 1px solid #cfd6dd; border-radius: 6px; padding: 9px; background: white; }
textarea { min-height: 130px; resize: vertical; font-family: ui-monospace, monospace; line-height: 1.45; }
.actions { display: flex; align-items: center; gap: 12px; margin-top: 12px; }
button { border: 0; border-radius: 6px; padding: 10px 18px; color: white; background: #2563eb; cursor: pointer; }
button:disabled { opacity: .55; cursor: wait; }
#status { color: #667085; }
#status.error { color: #b42318; }
#chart { height: 560px; margin-top: 18px; }
.table-wrap { display: none; max-height: 560px; overflow: auto; margin-top: 18px; }
table { width: 100%; border-collapse: collapse; background: white; }
th, td { padding: 9px 11px; border: 1px solid #e4e7ec; text-align: left; white-space: nowrap; }
th { position: sticky; top: 0; background: #f9fafb; }
@media (max-width: 760px) { .row { grid-template-columns: 1fr; } main { width: calc(100% - 20px); } }
</style>
</head>
<body>
<main>
<h1>Analytics graphs</h1>
<form id="query-form" class="panel">
<div class="row">
<label>Profile<input id="profile" required autocomplete="off"></label>
<label>Bearer token<input id="token" type="password" autocomplete="off"></label>
<label>Chart
<select id="chart-type">
<option value="bar">Bar</option>
<option value="line">Line</option>
<option value="pie">Pie</option>
<option value="scatter">Scatter</option>
<option value="table">Table</option>
</select>
</label>
<label>Max rows<input id="max-rows" type="number" min="1" value="1000"></label>
</div>
<label>SQL<textarea id="sql" required spellcheck="false" placeholder="SELECT category, SUM(amount) AS total FROM sales GROUP BY category"></textarea></label>
<div class="actions">
<button id="run" type="submit">Run query</button>
<span id="status"></span>
</div>
</form>
<div id="chart"></div>
<div id="table-wrap" class="table-wrap"><table id="table"></table></div>
</main>
<script>
const form = document.querySelector('#query-form');
const status = document.querySelector('#status');
const runButton = document.querySelector('#run');
const chartElement = document.querySelector('#chart');
const tableWrap = document.querySelector('#table-wrap');
const table = document.querySelector('#table');
const chart = echarts.init(chartElement);
let lastResult = null;
form.addEventListener('submit', async (event) => {
event.preventDefault();
runButton.disabled = true;
setStatus('Running…');
try {
const response = await fetch('/api/query', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
profile_name: document.querySelector('#profile').value,
token: document.querySelector('#token').value,
sql: document.querySelector('#sql').value,
max_rows: Number(document.querySelector('#max-rows').value)
})
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || `Request failed (${response.status})`);
lastResult = result;
render(result);
setStatus(`${result.row_count} rows in ${result.elapsed_ms} ms${result.truncated ? ' (truncated)' : ''}`);
} catch (error) {
setStatus(error.message, true);
} finally {
runButton.disabled = false;
}
});
document.querySelector('#chart-type').addEventListener('change', () => {
if (lastResult) render(lastResult);
});
window.addEventListener('resize', () => chart.resize());
function render(result) {
const type = document.querySelector('#chart-type').value;
if (type === 'table') return renderTable(result);
tableWrap.style.display = 'none';
chartElement.style.display = 'block';
if (!result.columns.length) {
chart.clear();
return;
}
const names = result.columns.map(column => column.name);
const rows = result.rows;
let option;
if (type === 'pie') {
option = {
tooltip: { trigger: 'item' },
legend: { type: 'scroll', bottom: 0 },
series: [{ type: 'pie', radius: ['25%', '68%'], data: rows.map(row => ({ name: String(row[0] ?? ''), value: numeric(row[1]) })) }]
};
} else if (type === 'scatter') {
option = {
tooltip: { trigger: 'item' },
xAxis: { name: names[0], type: 'value' },
yAxis: { name: names[1], type: 'value' },
series: [{ name: names[1], type: 'scatter', data: rows.map(row => [numeric(row[0]), numeric(row[1])]) }]
};
} else {
option = {
tooltip: { trigger: 'axis' },
legend: { type: 'scroll', bottom: 0 },
grid: { left: 55, right: 25, top: 35, bottom: 70, containLabel: true },
xAxis: { type: 'category', data: rows.map(row => String(row[0] ?? '')) },
yAxis: { type: 'value' },
series: names.slice(1).map((name, index) => ({ name, type, data: rows.map(row => numeric(row[index + 1])), smooth: type === 'line' }))
};
}
chart.setOption(option, true);
chart.resize();
}
function renderTable(result) {
chartElement.style.display = 'none';
tableWrap.style.display = 'block';
const header = `<thead><tr>${result.columns.map(column => `<th>${escapeHtml(column.name)}</th>`).join('')}</tr></thead>`;
const body = `<tbody>${result.rows.map(row => `<tr>${row.map(value => `<td>${escapeHtml(value ?? '')}</td>`).join('')}</tr>`).join('')}</tbody>`;
table.innerHTML = header + body;
}
function numeric(value) {
const number = Number(value);
return Number.isFinite(number) ? number : null;
}
function escapeHtml(value) {
const element = document.createElement('div');
element.textContent = String(value);
return element.innerHTML;
}
function setStatus(message, error = false) {
status.textContent = message;
status.classList.toggle('error', error);
}
</script>
</body>
</html>