:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(pgapi): API + MCP server over the pgcollector stats database (#90492)
Nick Beste622e22afeeb
diff --git a/.github/rust-images.yml b/.github/rust-images.ymlindex e265e9632004..0dee081df674 100644--- a/.github/rust-images.yml+++ b/.github/rust-images.yml@@ -100,6 +100,12 @@dockerfile: ./rust/Dockerfileproject: wb2br45dsr # pg-monitoring+# API + MCP server over the pgcollector stats database (Postgres telemetry).+# Internal, edge-authenticated (Cognito ingress + Tailscale whois). See rust/pgapi.+- image: pgapi+ dockerfile: ./rust/Dockerfile+ project: wb2br45dsr # pg-monitoring+- image: kafka-deduplicatordockerfile: ./rust/Dockerfileproject: vznmbshh6qdiff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex dd82068986a4..6610cffb1304 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -162,6 +162,7 @@ jobs:"ingestion-consumer": 20,"ingestion-control-plane": 41,"pgcollector": 45,+ "pgapi": 40,"k8s-awareness": 116,"kafka-assigner": 175,"kafka-assigner-proto": 5,diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.ymlindex c6511e3313cc..a679212f6f43 100644--- a/.github/workflows/rust-docker-build.yml+++ b/.github/workflows/rust-docker-build.yml@@ -180,6 +180,9 @@ jobs:- release: pgcollectordigest_key: pgcollectorvalues_key: image+ - release: pgapi+ digest_key: pgapi+ values_key: image- release: kafka-deduplicatordigest_key: kafka-deduplicatorvalues_key: imagediff --git a/docs/internal/pgapi.md b/docs/internal/pgapi.mdnew file mode 100644index 000000000000..2d2915ebfd4a--- /dev/null+++ b/docs/internal/pgapi.md@@ -0,0 +1,64 @@+# pgapi — Postgres telemetry API and MCP server++`rust/pgapi` serves the telemetry collected by `rust/pgcollector` (see+[pgcollector.md](pgcollector.md)) as a read-only REST API, an MCP server and a+small embedded UI. Crate-level details live in+[`rust/pgapi/README.md`](../../rust/pgapi/README.md); this page is the service+contract.++## Surfaces++| path | what | auth |+| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |+| `/api/v1/*` | JSON API: servers, overview, queries, activity, tables, indexes, vacuum, events, logs, system, schema, settings, collector health, guarded raw SQL | identity required |+| `/mcp` | MCP streamable HTTP, 17 read-only tools over the same query layer | identity required |+| `/` | embedded UI over `/api/v1` | identity required |+| `/healthz`, `/readyz`, `/metrics` | probes and Prometheus | none |++## Identity and authorization++The app runs no OAuth flow. Identity is established at the edge and read from+headers, each source bound to the ingress that sets it:++1. `Tailscale-User-Login` — only when `PGAPI_TRUST_TAILSCALE=1` **and** the+ request `Host` is a tailnet host (`PGAPI_TAILSCALE_HOSTS`, default+ `*.ts.net`), so a forged header on the Cognito host is ignored. The deploy+ must pair this with a NetworkPolicy admitting only the Tailscale operator's+ proxy pods.+2. `x-amzn-oidc-data` — ALB + Cognito JWT, verified ES256 against the regional+ ALB key endpoint; issuer must be a Cognito pool in `PGAPI_ALB_REGION`, the+ token must be minted for `PGAPI_ALB_CLIENT_ID` and signed by the ALB in+ `PGAPI_ALB_ARN` (JOSE `signer`), and `email_verified` must be true.+3. `X-Auth-Request-Email` — in-cluster auth gateway, only with+ `PGAPI_TRUST_GATEWAY=1`.+4. `PGAPI_DEV_USER` with `PGAPI_DEV_MODE=1` — local development only.++Authorization is by email domain (`PGAPI_ALLOWED_DOMAINS`, default+`posthog.com`) or explicit list (`PGAPI_ALLOWED_EMAILS`). There is one role:+everything is read-only. Every request is logged with the caller's email and+identity source.++## Data sensitivity++The stats database holds statement text from every monitored cluster. The+collector redacts string literals before storing log-derived statements, but+table names, query shapes and plan parameters are visible to anyone who can+authenticate. Keep the audience to engineering.++## Raw SQL tool++`GET /api/v1/sql` and the `query_stats_db` MCP tool run a single+`SELECT`/`WITH`/`EXPLAIN` against the stats database inside a read-only+transaction with a 15 s timeout under an 8 MiB serialised-response budget+(rows are streamed and the query cancelled past it), then `DISCARD ALL` the+session. Calls to+side-effecting functions (`pg_sleep`, advisory locks, `set_config`,+`pg_terminate_backend`, stats resets, file/backup functions, `dblink`, …) are+refused up front. The database+user is a read-only role. This is for agents answering questions the fixed+tools do not cover.++## Configuration++Environment variables are documented in `rust/pgapi/src/main.rs` (`--help`).+Deployment values for the golden chart are in `rust/pgapi/values.example.yaml`.diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex d574c7828336..55e7c45c67e9 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1582,6 +1582,12 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"+[[package]]name = "base64-simd"version = "0.8.0"@@ -3475,6 +3481,16 @@ dependencies = ["darling_macro 0.23.0",]+[[package]]+name = "darling"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"+dependencies = [+ "darling_core 0.24.1",+ "darling_macro 0.24.1",+]+[[package]]name = "darling_core"version = "0.20.11"@@ -3516,6 +3532,19 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "darling_core"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 3.0.3",+]+[[package]]name = "darling_macro"version = "0.20.11"@@ -3549,6 +3578,17 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "darling_macro"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"+dependencies = [+ "darling_core 0.24.1",+ "quote",+ "syn 3.0.3",+]+[[package]]name = "dary_heap"version = "0.3.9"@@ -8440,6 +8480,12 @@ version = "1.0.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"+[[package]]+name = "pastey"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"+[[package]]name = "pathdiff"version = "0.2.3"@@ -8898,6 +8944,35 @@ dependencies = ["serde",]+[[package]]+name = "pgapi"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum 0.7.9",+ "base64 0.22.1",+ "chrono",+ "clap",+ "deadpool-postgres",+ "futures-util",+ "humantime",+ "jsonwebtoken",+ "once_cell",+ "prometheus",+ "regex",+ "reqwest 0.12.28",+ "rmcp",+ "rust_decimal",+ "schemars 1.2.1",+ "serde",+ "serde_json",+ "tokio",+ "tokio-postgres",+ "tower-http 0.5.2",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "pgcollector"version = "0.1.0"@@ -10649,6 +10724,51 @@ version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422"+[[package]]+name = "rmcp"+version = "3.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a15bc53261a9dc37e105df006e4656c598379a8f9581f8950debb130f27a7cf"+dependencies = [+ "async-trait",+ "base64 0.23.1",+ "bytes",+ "chrono",+ "futures",+ "http 1.4.0",+ "http-body 1.0.1",+ "http-body-util",+ "indexmap 2.13.0",+ "pastey",+ "pin-project-lite",+ "rand 0.10.2",+ "rmcp-macros",+ "schemars 1.2.1",+ "serde",+ "serde_json",+ "sse-stream",+ "thiserror 2.0.18",+ "tokio",+ "tokio-stream",+ "tokio-util",+ "tower-service",+ "tracing",+ "uuid",+]++[[package]]+name = "rmcp-macros"+version = "3.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a85d45508e9b4ba024fe996c2638799635d75b6dd0ba8f32ccf08f8026f0c780"+dependencies = [+ "darling 0.24.1",+ "proc-macro2",+ "quote",+ "serde_json",+ "syn 3.0.3",+]+[[package]]name = "roaring"version = "0.11.4"@@ -10997,12 +11117,26 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"dependencies = [+ "chrono","dyn-clone","ref-cast",+ "schemars_derive","serde","serde_json",]+[[package]]+name = "schemars_derive"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 2.0.117",+]+[[package]]name = "scoped-tls"version = "1.0.1"@@ -11871,6 +12005,19 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "sse-stream"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c123f296ade4ec4b8b0f6162116e6629f5146922ca5ab40ca9d3c2e73ab4761e"+dependencies = [+ "bytes",+ "futures-util",+ "http-body 1.0.1",+ "http-body-util",+ "pin-project-lite",+]+[[package]]name = "stable_deref_trait"version = "1.2.1"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 4a60110dfd6b..72d878a0b627 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -72,6 +72,7 @@ members = ["affected-services","property-vals-rs","pgcollector",+ "pgapi",]# NOTE: cargo allows only one crate with `links = "python"` (i.e. one pyo3 version) perdiff --git a/rust/pgapi/Cargo.toml b/rust/pgapi/Cargo.tomlnew file mode 100644index 000000000000..41a02e8f5d14--- /dev/null+++ b/rust/pgapi/Cargo.toml@@ -0,0 +1,34 @@+[package]+name = "pgapi"+version = "0.1.0"+edition = "2021"+publish = false+description = "API + MCP server over the pgcollector stats database"++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true }+base64 = { workspace = true }+chrono = { workspace = true }+clap = { workspace = true, features = ["env"] }+deadpool-postgres = "0.14"+futures-util = { workspace = true }+humantime = { workspace = true }+jsonwebtoken = "8"+once_cell = { workspace = true }+prometheus = "0.13"+regex = { workspace = true }+reqwest = { workspace = true }+rmcp = { version = "3", features = ["server", "macros", "transport-streamable-http-server"] }+rust_decimal = { version = "1", features = ["db-tokio-postgres"] }+schemars = "1"+serde = { workspace = true }+serde_json = { workspace = true }+tokio = { workspace = true }+tokio-postgres = { version = "0.7", features = ["with-chrono-0_4", "with-serde_json-1"] }+tower-http = { workspace = true }+tracing = { workspace = true }+tracing-subscriber = { workspace = true }++[lints]+workspace = truediff --git a/rust/pgapi/README.md b/rust/pgapi/README.mdnew file mode 100644index 000000000000..f2e44fb73132--- /dev/null+++ b/rust/pgapi/README.md@@ -0,0 +1,76 @@+# pgapi — API + MCP server over the pgcollector stats database++Read-only REST API and MCP (streamable HTTP) server for the Postgres telemetry+collected by `rust/pgcollector`. One binary, one port: `/api/v1/*`, `/mcp`,+`/healthz`, `/readyz`, `/metrics`.++## Run locally++```sh+PGAPI_DEV_MODE=1 [email protected] \+ cargo run -p pgapi -- --database-url postgres://.../pgcollector+curl localhost:3400/api/v1/servers+curl "localhost:3400/api/v1/servers/<id>/queries?since=1h&order=total_exec_time"+```++MCP client config (Claude Code / Desktop): `{"type": "http", "url": "http://localhost:3400/mcp"}`.+17 tools: `list_servers`, `server_overview`, `top_queries`, `query_detail`,+`wait_events`, `current_activity`, `table_stats`, `index_stats`,+`vacuum_status`, `events`, `settings`, `schema`, `log_errors`, `system_stats`,+`collector_health`, `describe_stats_schema`, `query_stats_db` (guarded raw SQL).++## Authentication++No OAuth flow in the app. Identity is established at the edge and read from+headers, in priority order (`src/auth.rs`):++1. `Tailscale-User-Login` — Tailscale ingress with `whois: true`; trusted only+ with `PGAPI_TRUST_TAILSCALE=1` **and** on a tailnet `Host`+ (`PGAPI_TAILSCALE_HOSTS`, default any `*.ts.net`), so the header is ignored+ when a request arrives through another ingress. Must be paired with a+ NetworkPolicy admitting only `tailscale.com/managed=true` proxy pods (see+ `values.example.yaml`). This is the path for MCP / CLI callers.+2. `x-amzn-oidc-data` — ALB + Cognito (`ingress.internal: true`); verified+ ES256 against `https://public-keys.auth.elb.<region>.amazonaws.com/<kid>`,+ issuer must be a Cognito pool in `PGAPI_ALB_REGION`, the token must be for+ `PGAPI_ALB_CLIENT_ID` and signed by `PGAPI_ALB_ARN` (the JOSE `signer`;+ all three required together), `email_verified` must be true.+ Browser path.+3. `X-Auth-Request-Email` — the in-cluster auth gateway, if/when adopted+ (`PGAPI_TRUST_GATEWAY=1`).+4. `PGAPI_DEV_USER` in dev mode.++Authorisation: `PGAPI_ALLOWED_DOMAINS` (default `posthog.com`) and/or+`PGAPI_ALLOWED_EMAILS`. Everything is read-only; the DB session is forced+`default_transaction_read_only`, and the raw-SQL tool runs each statement in a+read-only transaction with a 15 s timeout followed by `DISCARD ALL`, so+advisory locks or session settings cannot outlive a request, streams rows+under an 8 MiB response budget, and refuses calls+to known side-effecting functions (`pg_sleep`, advisory locks, `set_config`,+backend signalling, stats resets, file/backup functions, `dblink`). Every request is+logged with the caller's email and identity source.++This mirrors hosthog-api's dual-host pattern: humans use the Cognito-gated+`*.posthog.dev` host, agents use the tailnet host — Cognito can't+authenticate headless clients.++## Deploying++`values.example.yaml` is the golden-chart values file (ingress.internal ++tailscaleIngress + NetworkPolicy + read-only `psql`). Also needed:++* Tailscale ACL (`posthog-cloud-infra/tailnet-policy.hujson`): `tag:pgapi`+ owned by `tag:k8s-operator`, `group:[email protected] → tag:pgapi:443`,+ plus the positive/negative tests — copy the `tag:secrets-ui` block.+* Egress to the ALB public-key endpoint for token verification.+* A `users_readonly` user for the stats DB.++## Layout++```text+src/auth.rs identity middleware+src/queries.rs every question the API can answer, as SQL → JSON (shared by REST + MCP)+src/api.rs REST routes+src/mcp.rs MCP tools+src/db.rs read-only pool, row → JSON+```diff --git a/rust/pgapi/src/api.rs b/rust/pgapi/src/api.rsnew file mode 100644index 000000000000..6f1eb75d65e1--- /dev/null+++ b/rust/pgapi/src/api.rs@@ -0,0 +1,235 @@+//! REST surface. Handlers are thin: parse params, call `queries`, return JSON.++use crate::auth::Principal;+use crate::config::Range;+use crate::queries as q;+use crate::AppState;+use axum::{+ extract::{Extension, Path, Query, State},+ http::StatusCode,+ response::{IntoResponse, Json, Response},+ routing::get,+ Router,+};+use serde::Deserialize;+use std::sync::Arc;++type S = State<Arc<AppState>>;++pub struct ApiError(anyhow::Error);+impl<E: Into<anyhow::Error>> From<E> for ApiError {+ fn from(e: E) -> Self {+ Self(e.into())+ }+}+impl IntoResponse for ApiError {+ fn into_response(self) -> Response {+ let msg = format!("{:#}", self.0);+ let code = if msg.contains("range") || msg.contains("allowed") || msg.contains("only") {+ StatusCode::BAD_REQUEST+ } else {+ StatusCode::INTERNAL_SERVER_ERROR+ };+ (code, Json(serde_json::json!({ "error": msg }))).into_response()+ }+}+type R = Result<Json<serde_json::Value>, ApiError>;++pub fn router() -> Router<Arc<AppState>> {+ Router::new()+ .route("/me", get(me))+ .route("/servers", get(servers))+ .route("/servers/:server/overview", get(overview))+ .route("/servers/:server/queries", get(top_queries))+ .route("/servers/:server/queries/:queryid", get(query_detail))+ .route("/servers/:server/waits", get(waits))+ .route("/servers/:server/activity", get(activity))+ .route("/servers/:server/tables", get(tables))+ .route("/servers/:server/indexes", get(indexes))+ .route("/servers/:server/vacuum", get(vacuum))+ .route("/servers/:server/events", get(events))+ .route("/servers/:server/settings", get(settings))+ .route("/servers/:server/schema", get(schema))+ .route("/servers/:server/logs", get(logs))+ .route("/servers/:server/system", get(system))+ .route("/collector/health", get(collector_health))+ .route("/sql", get(sql))+ .route("/stats-schema", get(stats_schema))+}++async fn me(Extension(p): Extension<Principal>) -> R {+ Ok(Json(serde_json::to_value(p)?))+}+async fn servers(State(s): S) -> R {+ Ok(Json(q::servers(&s.db).await?))+}++async fn overview(State(s): S, Path(server): Path<String>, Query(r): Query<Range>) -> R {+ let (f, t) = r.resolve()?;+ Ok(Json(q::overview(&s.db, &server, f, t).await?))+}++#[derive(Deserialize)]+struct TopQ {+ #[serde(flatten)]+ range: Range,+ datname: Option<String>,+ #[serde(default = "d_order")]+ order: String,+ #[serde(default = "d_limit")]+ limit: i64,+}+fn d_order() -> String {+ "total_exec_time".into()+}+fn d_limit() -> i64 {+ 50+}+async fn top_queries(State(s): S, Path(server): Path<String>, Query(p): Query<TopQ>) -> R {+ let (f, t) = p.range.resolve()?;+ Ok(Json(+ q::top_queries(+ &s.db,+ &server,+ f,+ t,+ p.datname.as_deref(),+ &p.order,+ p.limit.clamp(1, 500),+ )+ .await?,+ ))+}+async fn query_detail(+ State(s): S,+ Path((server, queryid)): Path<(String, i64)>,+ Query(r): Query<Range>,+) -> R {+ let (f, t) = r.resolve()?;+ Ok(Json(q::query_detail(&s.db, &server, queryid, f, t).await?))+}+#[derive(Deserialize)]+struct WaitsQ {+ #[serde(flatten)]+ range: Range,+ #[serde(default = "d_bucket")]+ bucket: String,+}+fn d_bucket() -> String {+ "1m".into()+}+async fn waits(State(s): S, Path(server): Path<String>, Query(p): Query<WaitsQ>) -> R {+ let (f, t) = p.range.resolve()?;+ Ok(Json(q::wait_events(&s.db, &server, f, t, &p.bucket).await?))+}+async fn activity(State(s): S, Path(server): Path<String>) -> R {+ Ok(Json(q::current_activity(&s.db, &server).await?))+}++#[derive(Deserialize)]+struct DbQ {+ #[serde(flatten)]+ range: Range,+ datname: String,+ #[serde(default = "d_limit")]+ limit: i64,+}+async fn tables(State(s): S, Path(server): Path<String>, Query(p): Query<DbQ>) -> R {+ let (f, t) = p.range.resolve()?;+ Ok(Json(+ q::tables(&s.db, &server, &p.datname, f, t, p.limit.clamp(1, 2000)).await?,+ ))+}+async fn indexes(State(s): S, Path(server): Path<String>, Query(p): Query<DbQ>) -> R {+ let (f, t) = p.range.resolve()?;+ Ok(Json(q::indexes(&s.db, &server, &p.datname, f, t).await?))+}+#[derive(Deserialize)]+struct OptDbQ {+ #[serde(flatten)]+ range: Range,+ datname: Option<String>,+ kind: Option<String>,+ relname: Option<String>,+ #[serde(default = "d_limit")]+ limit: i64,+ #[serde(default)]+ non_default: bool,+}+async fn vacuum(State(s): S, Path(server): Path<String>, Query(p): Query<OptDbQ>) -> R {+ let (f, t) = p.range.resolve()?;+ Ok(Json(+ q::vacuum(&s.db, &server, p.datname.as_deref(), f, t).await?,+ ))+}+async fn events(State(s): S, Path(server): Path<String>, Query(p): Query<OptDbQ>) -> R {+ let (f, t) = p.range.resolve()?;+ Ok(Json(+ q::events(+ &s.db,+ &server,+ f,+ t,+ p.kind.as_deref(),+ p.limit.clamp(1, 1000),+ )+ .await?,+ ))+}+async fn settings(State(s): S, Path(server): Path<String>, Query(p): Query<OptDbQ>) -> R {+ Ok(Json(q::settings(&s.db, &server, p.non_default).await?))+}+async fn schema(State(s): S, Path(server): Path<String>, Query(p): Query<OptDbQ>) -> R {+ let datname = p+ .datname+ .ok_or_else(|| anyhow::anyhow!("datname is required"))?;+ Ok(Json(+ q::schema(&s.db, &server, &datname, p.relname.as_deref()).await?,+ ))+}+async fn logs(State(s): S, Path(server): Path<String>, Query(p): Query<OptDbQ>) -> R {+ let (f, t) = p.range.resolve()?;+ Ok(Json(+ q::log_errors(&s.db, &server, f, t, p.limit.clamp(1, 1000)).await?,+ ))+}+async fn system(State(s): S, Path(server): Path<String>, Query(r): Query<Range>) -> R {+ let (f, t) = r.resolve()?;+ Ok(Json(q::system(&s.db, &server, f, t).await?))+}+async fn collector_health(State(s): S) -> R {+ Ok(Json(q::collector_health(&s.db).await?))+}++#[derive(Deserialize)]+struct SqlQ {+ sql: String,+ #[serde(default = "d_sql_limit")]+ limit: i64,+}+fn d_sql_limit() -> i64 {+ 200+}+async fn sql(State(s): S, Extension(p): Extension<Principal>, Query(qs): Query<SqlQ>) -> R {+ tracing::info!(email = p.email, sql = qs.sql, "raw sql");+ Ok(Json(q::raw_sql(&s.db, &qs.sql, qs.limit).await?))+}+async fn stats_schema(State(s): S) -> R {+ Ok(Json(q::schema_of_stats_db(&s.db).await?))+}++pub async fn readyz(State(s): S) -> Response {+ if s.db.ping().await {+ (StatusCode::OK, "ready").into_response()+ } else {+ (StatusCode::SERVICE_UNAVAILABLE, "stats db unreachable").into_response()+ }+}+pub async fn metrics() -> Response {+ use prometheus::Encoder;+ let mut buf = Vec::new();+ prometheus::TextEncoder::new()+ .encode(&prometheus::gather(), &mut buf)+ .ok();+ ([("content-type", "text/plain; version=0.0.4")], buf).into_response()+}diff --git a/rust/pgapi/src/auth.rs b/rust/pgapi/src/auth.rsnew file mode 100644index 000000000000..dc0a8659f518--- /dev/null+++ b/rust/pgapi/src/auth.rs@@ -0,0 +1,301 @@+//! Identity: who is calling. No OAuth flow of our own — identity is established at+//! the edge and reaches us as headers, in this priority order:+//!+//! 1. `Tailscale-User-Login` — injected by the Tailscale ingress proxy (`whois: true`).+//! Trusted only when `PGAPI_TRUST_TAILSCALE=1`, which must be paired with a+//! NetworkPolicy admitting only `tailscale.com/managed=true` proxy pods.+//! 2. `x-amzn-oidc-data` — the ALB+Cognito JWT (`ingress.internal: true`). Verified+//! (ES256) against the regional ALB public-key endpoint; never trusted unverified.+//! 3. `X-Auth-Request-Email` — the in-cluster auth gateway (heimdall). Trusted only+//! when `PGAPI_TRUST_GATEWAY=1` (NetworkPolicy to the gateway's Envoy).+//! 4. `PGAPI_DEV_USER` in dev mode.+//!+//! Then authorisation: the email must match an allowed domain or the explicit list.+//! Everything the API serves is read-only, so there is one role today.++use crate::AppState;+use axum::{+ body::Body,+ extract::State,+ http::{Request, StatusCode},+ middleware::Next,+ response::{IntoResponse, Response},+};+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::sync::{Arc, RwLock};++#[derive(Debug, Clone, Serialize)]+pub struct Principal {+ pub email: String,+ pub source: &'static str,+}++pub struct AlbConfig {+ pub region: String,+ pub client_id: String,+ /// ARN of the ALB that fronts this service; the token's `signer` header must match,+ /// otherwise a token minted by another ALB in the region with the same client id+ /// would be accepted.+ pub arn: String,+ /// kid → PEM public key, cached.+ pub keys: RwLock<HashMap<String, String>>,+}++pub struct AuthConfig {+ pub allowed_domains: Vec<String>,+ pub allowed_emails: Vec<String>,+ pub trust_tailscale: bool,+ /// Hosts (from the `Host` header) on which `Tailscale-User-Login` is trusted.+ /// Empty = any host ending in `.ts.net`. A request arriving on the Cognito+ /// ingress host can carry a forged header, so the header only counts on the+ /// tailnet host that the Tailscale proxy terminates.+ pub tailscale_hosts: Vec<String>,+ pub trust_gateway: bool,+ pub alb: Option<AlbConfig>,+ pub dev_user: Option<String>,+}++#[derive(Debug, Deserialize)]+struct AlbClaims {+ email: Option<String>,+ #[serde(default)]+ email_verified: Option<serde_json::Value>,+ iss: String,+}++impl AuthConfig {+ fn authorized(&self, email: &str) -> bool {+ let email = email.to_ascii_lowercase();+ if self+ .allowed_emails+ .iter()+ .any(|e| e.eq_ignore_ascii_case(&email))+ {+ return true;+ }+ if self.allowed_domains.is_empty() {+ return true;+ }+ .rsplit_once('@')+ .map(|(_, d)| {+ self.allowed_domains+ .iter()+ .any(|a| a.eq_ignore_ascii_case(d))+ })+ .unwrap_or(false)+ }++ fn on_tailscale_host(&self, headers: &axum::http::HeaderMap) -> bool {+ let host = headers+ .get("host")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .split(':')+ .next()+ .unwrap_or("")+ .to_ascii_lowercase();+ if self.tailscale_hosts.is_empty() {+ host.ends_with(".ts.net")+ } else {+ self.tailscale_hosts+ .iter()+ .any(|h| h.eq_ignore_ascii_case(&host))+ }+ }++ async fn identify(+ &self,+ headers: &axum::http::HeaderMap,+ ) -> Result<Principal, (StatusCode, String)> {+ let h = |n: &str| {+ headers+ .get(n)+ .and_then(|v| v.to_str().ok())+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ };++ if self.trust_tailscale && self.on_tailscale_host(headers) {+ if let Some(login) = h("tailscale-user-login") {+ return Ok(Principal {+ email: login,+ source: "tailscale",+ });+ }+ }+ if let Some(alb) = &self.alb {+ if let Some(token) = h("x-amzn-oidc-data") {+ let email = verify_alb_token(alb, &token)+ .await+ .map_err(|e| (StatusCode::UNAUTHORIZED, format!("invalid ALB token: {e}")))?;+ return Ok(Principal {+ email,+ source: "cognito",+ });+ }+ }+ if self.trust_gateway {+ if let Some(email) = h("x-auth-request-email") {+ return Ok(Principal {+ email,+ source: "gateway",+ });+ }+ }+ if let Some(u) = &self.dev_user {+ return Ok(Principal {+ email: u.clone(),+ source: "dev",+ });+ }+ Err((+ StatusCode::UNAUTHORIZED,+ "no identity: reach this service through the internal ingress or the tailnet".into(),+ ))+ }+}++/// ALB signs `x-amzn-oidc-data` with ES256; the public key is served per `kid` at+/// https://public-keys.auth.elb.<region>.amazonaws.com/<kid>. The header's base64+/// segments may lack padding, and ALB's signature uses the raw (r,s) form+/// jsonwebtoken expects, so the standard decoder works after padding fix-up.+async fn verify_alb_token(alb: &AlbConfig, token: &str) -> anyhow::Result<String> {+ use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};+ let token = fix_padding(token);+ let header = decode_header(&token)?;+ anyhow::ensure!(+ header.alg == Algorithm::ES256,+ "unexpected alg {:?}",+ header.alg+ );+ let kid = header+ .kid+ .ok_or_else(|| anyhow::anyhow!("token has no kid"))?;+ anyhow::ensure!(+ kid.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'),+ "bad kid"+ );+ let pem = {+ let cached = alb.keys.read().unwrap().get(&kid).cloned();+ match cached {+ Some(p) => p,+ None => {+ let url = format!(+ "https://public-keys.auth.elb.{}.amazonaws.com/{kid}",+ alb.region+ );+ let p = reqwest::Client::new()+ .get(&url)+ .send()+ .await?+ .error_for_status()?+ .text()+ .await?;+ alb.keys.write().unwrap().insert(kid.clone(), p.clone());+ p+ }+ }+ };+ let key = DecodingKey::from_ec_pem(pem.as_bytes())?;+ let mut v = Validation::new(Algorithm::ES256);+ v.validate_exp = true;+ v.set_required_spec_claims(&["exp"]);+ let data = decode::<AlbClaims>(&token, &key, &v)?;+ // Issuer must be a Cognito user pool in the ALB's region.+ let want_iss = format!("https://cognito-idp.{}.amazonaws.com/", alb.region);+ anyhow::ensure!(+ data.claims.iss.starts_with(&want_iss),+ "unexpected issuer {}",+ data.claims.iss+ );+ // The token must be minted for our app client by our ALB; both are recorded in the+ // JOSE header (`client`, `signer`) that the signature covers.+ let got = header_field(&token, "client")+ .ok_or_else(|| anyhow::anyhow!("token has no client in header"))?;+ anyhow::ensure!(alb.client_id == got, "token for another client ({got})");+ let signer = header_field(&token, "signer")+ .ok_or_else(|| anyhow::anyhow!("token has no signer in header"))?;+ anyhow::ensure!(+ alb.arn == signer,+ "token signed by another load balancer ({signer})"+ );+ let email = data+ .claims+ .ok_or_else(|| anyhow::anyhow!("token has no email claim"))?;+ // Cognito emits email_verified as a bool or as the strings "true"/"false"; only an+ // explicit true is a verified address. Missing means unverified.+ let verified = match &data.claims.email_verified {+ Some(serde_json::Value::Bool(b)) => *b,+ Some(serde_json::Value::String(s)) => s.eq_ignore_ascii_case("true"),+ _ => false,+ };+ anyhow::ensure!(verified, "email not verified");+ Ok(email)+}++/// ALB puts the Cognito app client id (`client`) and its own ARN (`signer`) in the JOSE header.+fn header_field(token: &str, key: &str) -> Option<String> {+ use base64::Engine;+ let h = token.split('.').next()?;+ let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD+ .decode(h.trim_end_matches('='))+ .ok()?;+ serde_json::from_slice::<serde_json::Value>(&bytes)+ .ok()?+ .get(key)?+ .as_str()+ .map(str::to_string)+}++fn fix_padding(token: &str) -> String {+ token+ .split('.')+ .map(|p| p.trim_end_matches('='))+ .collect::<Vec<_>>()+ .join(".")+}++pub async fn require_identity(+ State(state): State<Arc<AppState>>,+ mut req: Request<Body>,+ next: Next,+) -> Response {+ if !state.allowed_hosts.is_empty() {+ let host = req+ .headers()+ .get("host")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .split(':')+ .next()+ .unwrap_or("")+ .to_string();+ if !state+ .allowed_hosts+ .iter()+ .any(|h| h.eq_ignore_ascii_case(&host))+ {+ return (StatusCode::FORBIDDEN, format!("host {host} not allowed")).into_response();+ }+ }+ let headers = req.headers().clone(); // Body is !Sync; don't hold &Request across awaits+ match state.auth.identify(&headers).await {+ Ok(p) => {+ if !state.auth.authorized(&p.email) {+ tracing::warn!(email = p.email, source = p.source, "forbidden");+ return (+ StatusCode::FORBIDDEN,+ format!("{} is not allowed to read pgcollector data", p.email),+ )+ .into_response();+ }+ tracing::info!(email = p.email, source = p.source, method = %req.method(), path = %req.uri().path(), "request");+ req.extensions_mut().insert(p);+ next.run(req).await+ }+ Err((code, msg)) => (code, msg).into_response(),+ }+}diff --git a/rust/pgapi/src/config.rs b/rust/pgapi/src/config.rsnew file mode 100644index 000000000000..932845a2addd--- /dev/null+++ b/rust/pgapi/src/config.rs@@ -0,0 +1,29 @@+//! Shared request-parameter helpers (time ranges etc.).++use chrono::{DateTime, Duration, Utc};+use serde::Deserialize;++#[derive(Debug, Clone, Deserialize, Default)]+pub struct Range {+ /// Look-back window like `15m`, `1h`, `24h` (default 1h) — or explicit `from`/`to`.+ pub since: Option<String>,+ pub from: Option<DateTime<Utc>>,+ pub to: Option<DateTime<Utc>>,+}++impl Range {+ pub fn resolve(&self) -> anyhow::Result<(DateTime<Utc>, DateTime<Utc>)> {+ let to = self.to.unwrap_or_else(Utc::now);+ let from = match (&self.from, &self.since) {+ (Some(f), _) => *f,+ (None, Some(s)) => to - Duration::from_std(humantime::parse_duration(s)?)?,+ (None, None) => to - Duration::hours(1),+ };+ anyhow::ensure!(from < to, "empty range");+ anyhow::ensure!(+ to - from <= Duration::days(31),+ "range too large (max 31 days)"+ );+ Ok((from, to))+ }+}diff --git a/rust/pgapi/src/db.rs b/rust/pgapi/src/db.rsnew file mode 100644index 000000000000..48e7292b276d--- /dev/null+++ b/rust/pgapi/src/db.rs@@ -0,0 +1,164 @@+//! Read-only access to the stats database, returning rows as JSON objects so the+//! REST and MCP layers can share every query without per-endpoint structs.++use anyhow::{Context, Result};+use chrono::{DateTime, Utc};+use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod};+use serde_json::{json, Map, Value};+use tokio_postgres::types::{ToSql, Type};+use tokio_postgres::NoTls;++/// Serialised-response ceiling for raw SQL. Row count is bounded by LIMIT; this bounds+/// bytes so a wide or `repeat()`-style query can't exhaust the pod's memory.+pub const RAW_SQL_MAX_BYTES: usize = 8 * 1024 * 1024;++#[derive(Clone)]+pub struct Db {+ pool: Pool,+}++impl Db {+ pub async fn connect(url: &str) -> Result<Self> {+ let cfg: tokio_postgres::Config = url.parse().context("parsing PGAPI_DATABASE_URL")?;+ let mgr = Manager::from_config(+ cfg,+ NoTls,+ ManagerConfig {+ recycling_method: RecyclingMethod::Fast,+ },+ );+ let pool = Pool::builder(mgr)+ .max_size(16)+ .post_create(deadpool_postgres::Hook::async_fn(|c, _| Box::pin(async move {+ // The API is read-only by construction; make the session enforce it too. A+ // connection that cannot be made read-only is rejected, never pooled.+ c.batch_execute("SET default_transaction_read_only = on; SET statement_timeout = 30000; SET application_name = 'pgapi'")+ .await+ .map_err(|e| {+ tracing::error!(error = %e, "could not apply read-only session settings; dropping connection");+ deadpool_postgres::HookError::Backend(e)+ })+ })))+ .build()?;+ let db = Self { pool };+ db.query("SELECT 1", &[])+ .await+ .context("stats database unreachable")?;+ Ok(db)+ }++ pub async fn ping(&self) -> bool {+ self.query("SELECT 1", &[]).await.is_ok()+ }++ pub async fn query(&self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> Result<Vec<Value>> {+ let c = self.pool.get().await?;+ let rows = c+ .query(sql, params)+ .await+ .with_context(|| format!("query failed: {}", sql.lines().next().unwrap_or("")))?;+ rows.iter().map(row_to_json).collect()+ }++ /// Run one statement in a read-only transaction with a short timeout, then reset+ /// the session with `DISCARD ALL` so nothing it did (advisory locks, temp objects,+ /// SET) outlives the request. If the reset fails the connection is dropped.+ pub async fn query_isolated(&self, sql: &str) -> Result<Value> {+ let mut c = self.pool.get().await?;+ let result = async {+ let tx = c.build_transaction().read_only(true).start().await?;+ tx.batch_execute("SET LOCAL statement_timeout = 15000; SET LOCAL lock_timeout = 1000")+ .await?;+ // Stream rows and stop once the serialised response would exceed the budget;+ // dropping the stream and rolling back cancels the server side. Row count is+ // capped by the caller's LIMIT, bytes are capped here.+ use futures_util::TryStreamExt;+ let params: [&(dyn ToSql + Sync); 0] = [];+ let stream = tx+ .query_raw(sql, params)+ .await+ .with_context(|| format!("query failed: {}", sql.lines().next().unwrap_or("")))?;+ let mut stream = std::pin::pin!(stream);+ let mut out = Vec::new();+ let mut bytes = 0usize;+ while let Some(row) = stream.try_next().await.context("query failed")? {+ let v = row_to_json(&row)?;+ bytes += serde_json::to_vec(&v).map(|b| b.len()).unwrap_or(0);+ anyhow::ensure!(+ bytes <= RAW_SQL_MAX_BYTES,+ "result exceeds {} MiB; narrow the query or select fewer columns",+ RAW_SQL_MAX_BYTES / (1024 * 1024)+ );+ out.push(v);+ }+ tx.rollback().await?;+ Ok::<_, anyhow::Error>(out)+ }+ .await;+ if c.batch_execute(+ "DISCARD ALL; SET default_transaction_read_only = on; SET statement_timeout = 30000",+ )+ .await+ .is_err()+ {+ // Don't hand a dirty session back to the pool.+ drop(deadpool_postgres::Object::take(c));+ }+ Ok(json!(result?))+ }++ pub async fn query_one(&self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> Result<Value> {+ Ok(self+ .query(sql, params)+ .await?+ .into_iter()+ .next()+ .unwrap_or(Value::Null))+ }+}++pub fn row_to_json(r: &tokio_postgres::Row) -> Result<Value> {+ let mut m = Map::new();+ for (i, col) in r.columns().iter().enumerate() {+ let v = match *col.type_() {+ Type::BOOL => r.try_get::<_, Option<bool>>(i)?.map(Value::from),+ Type::INT2 => r.try_get::<_, Option<i16>>(i)?.map(Value::from),+ Type::INT4 => r.try_get::<_, Option<i32>>(i)?.map(Value::from),+ // JavaScript numbers lose precision past 2^53; query/plan ids are full+ // int64 hashes, so ship those as strings.+ Type::INT8 => r.try_get::<_, Option<i64>>(i)?.map(|v| {+ if v.unsigned_abs() > (1u64 << 53) {+ Value::from(v.to_string())+ } else {+ Value::from(v)+ }+ }),+ Type::OID => r.try_get::<_, Option<u32>>(i)?.map(Value::from),+ Type::FLOAT4 => r.try_get::<_, Option<f32>>(i)?.map(|x| json!(x)),+ Type::FLOAT8 => r.try_get::<_, Option<f64>>(i)?.map(|x| json!(x)),+ Type::NUMERIC => r.try_get::<_, Option<rust_decimal::Decimal>>(i)?.map(|d| {+ let f: f64 = d.try_into().unwrap_or(f64::NAN);+ json!(f)+ }),+ Type::TIMESTAMPTZ => r.try_get::<_, Option<DateTime<Utc>>>(i)?.map(|t| json!(t)),+ Type::JSON | Type::JSONB => r.try_get::<_, Option<Value>>(i)?,+ // Functions returning void (raw SQL calling e.g. pg_advisory_lock) produce a+ // void column; render it as null rather than failing the whole row.+ Type::VOID => None,+ Type::TEXT_ARRAY | Type::VARCHAR_ARRAY | Type::NAME_ARRAY => {+ r.try_get::<_, Option<Vec<String>>>(i)?.map(|v| json!(v))+ }+ Type::INT8_ARRAY => r.try_get::<_, Option<Vec<i64>>>(i)?.map(|v| json!(v)),+ Type::TEXT | Type::VARCHAR | Type::NAME | Type::BPCHAR | Type::CHAR | Type::UNKNOWN => {+ r.try_get::<_, Option<String>>(i)?.map(Value::from)+ }+ _ => anyhow::bail!(+ "unsupported column type {} for {}; cast in SQL",+ col.type_(),+ col.name()+ ),+ };+ m.insert(col.name().to_string(), v.unwrap_or(Value::Null));+ }+ Ok(Value::Object(m))+}diff --git a/rust/pgapi/src/main.rs b/rust/pgapi/src/main.rsnew file mode 100644index 000000000000..f9e0a81ce896--- /dev/null+++ b/rust/pgapi/src/main.rs@@ -0,0 +1,165 @@+mod api;+mod auth;+mod config;+mod db;+mod mcp;+mod queries;+mod ui;++use anyhow::Result;+use axum::{middleware, routing::get, Router};+use clap::Parser;+use std::sync::Arc;+use tracing_subscriber::EnvFilter;++#[derive(Parser, Debug)]+#[command(+ name = "pgapi",+ about = "API + MCP server over the pgcollector stats database"+)]+struct Cli {+ #[arg(long, env = "PGAPI_DATABASE_URL")]+ database_url: String,+ #[arg(long, env = "PGAPI_LISTEN", default_value = "0.0.0.0:3400")]+ listen: String,+ /// Comma-separated email domains allowed to read (empty = any authenticated identity).+ #[arg(+ long,+ env = "PGAPI_ALLOWED_DOMAINS",+ default_value = "posthog.com",+ value_delimiter = ','+ )]+ allowed_domains: Vec<String>,+ /// Comma-separated explicit allowlist of emails (in addition to domains).+ #[arg(long, env = "PGAPI_ALLOWED_EMAILS", value_delimiter = ',')]+ allowed_emails: Vec<String>,+ /// Trust `Tailscale-User-Login` from the Tailscale ingress proxy. Only enable with a+ /// NetworkPolicy that restricts ingress to the operator's proxy pods.+ #[arg(long, env = "PGAPI_TRUST_TAILSCALE", default_value = "false", value_parser = parse_bool)]+ trust_tailscale: bool,+ /// Hosts on which `Tailscale-User-Login` is trusted (comma-separated). Empty = any+ /// host ending in `.ts.net`.+ #[arg(long, env = "PGAPI_TAILSCALE_HOSTS", value_delimiter = ',')]+ tailscale_hosts: Vec<String>,+ /// Verify ALB/Cognito `x-amzn-oidc-data` tokens (region for the ALB public key endpoint).+ /// Requires PGAPI_ALB_CLIENT_ID.+ #[arg(long, env = "PGAPI_ALB_REGION", requires_all = ["alb_client_id", "alb_arn"])]+ alb_region: Option<String>,+ /// Cognito app client id the ALB tokens must be minted for.+ #[arg(long, env = "PGAPI_ALB_CLIENT_ID")]+ alb_client_id: Option<String>,+ /// ARN of the ALB in front of this service; tokens signed by any other ALB are rejected.+ #[arg(long, env = "PGAPI_ALB_ARN")]+ alb_arn: Option<String>,+ /// Trust `X-Auth-Request-Email` from the in-cluster auth gateway (heimdall).+ #[arg(long, env = "PGAPI_TRUST_GATEWAY", default_value = "false", value_parser = parse_bool)]+ trust_gateway: bool,+ /// DEV ONLY: treat every request as this user. Refused unless PGAPI_DEV_MODE=1.+ #[arg(long, env = "PGAPI_DEV_USER")]+ dev_user: Option<String>,+ #[arg(long, env = "PGAPI_DEV_MODE", default_value = "false", value_parser = parse_bool)]+ dev_mode: bool,+ /// Hosts this server may be addressed as (DNS-rebinding guard for /mcp). Empty = any.+ #[arg(long, env = "PGAPI_ALLOWED_HOSTS", value_delimiter = ',')]+ allowed_hosts: Vec<String>,+}++/// Accept 1/0/true/false/yes/no/on/off so Helm `env:` values like "1" work.+fn parse_bool(s: &str) -> Result<bool, String> {+ match s.trim().to_ascii_lowercase().as_str() {+ "1" | "true" | "yes" | "on" => Ok(true),+ "0" | "false" | "no" | "off" | "" => Ok(false),+ o => Err(format!("expected a boolean, got {o:?}")),+ }+}++pub struct AppState {+ pub db: db::Db,+ pub auth: auth::AuthConfig,+ pub allowed_hosts: Vec<String>,+}++#[tokio::main]+async fn main() -> Result<()> {+ tracing_subscriber::fmt()+ .with_env_filter(+ EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,tokio_postgres=warn".into()),+ )+ .init();+ let cli = Cli::parse();+ if cli.dev_user.is_some() && !cli.dev_mode {+ anyhow::bail!("PGAPI_DEV_USER requires PGAPI_DEV_MODE=1");+ }+ let auth = auth::AuthConfig {+ allowed_domains: cli+ .allowed_domains+ .into_iter()+ .filter(|d| !d.is_empty())+ .collect(),+ allowed_emails: cli+ .allowed_emails+ .into_iter()+ .filter(|d| !d.is_empty())+ .collect(),+ trust_tailscale: cli.trust_tailscale,+ tailscale_hosts: cli+ .tailscale_hosts+ .into_iter()+ .filter(|h| !h.is_empty())+ .collect(),+ trust_gateway: cli.trust_gateway,+ alb: match (cli.alb_region, cli.alb_client_id, cli.alb_arn) {+ (Some(region), Some(client_id), Some(arn)) => Some(auth::AlbConfig {+ region,+ client_id,+ arn,+ keys: Default::default(),+ }),+ _ => None,+ },+ dev_user: cli.dev_user,+ };+ if auth.dev_user.is_some() {+ tracing::warn!(+ "DEV MODE: all requests authenticated as {:?}",+ auth.dev_user+ );+ }+ if !auth.trust_tailscale && !auth.trust_gateway && auth.alb.is_none() && auth.dev_user.is_none()+ {+ tracing::warn!("no identity source configured (PGAPI_TRUST_TAILSCALE / PGAPI_ALB_REGION / dev mode): every request will be 401");+ }++ let db = db::Db::connect(&cli.database_url).await?;+ let state = Arc::new(AppState {+ db,+ auth,+ allowed_hosts: cli+ .allowed_hosts+ .into_iter()+ .filter(|h| !h.is_empty())+ .collect(),+ });++ let protected = Router::new()+ .route("/", get(ui::index))+ .nest("/api/v1", api::router())+ .nest_service("/mcp", mcp::service(state.clone()))+ .route_layer(middleware::from_fn_with_state(+ state.clone(),+ auth::require_identity,+ ));++ let app = Router::new()+ .route("/healthz", get(|| async { "ok" }))+ .route("/readyz", get(api::readyz))+ .route("/metrics", get(api::metrics))+ .merge(protected)+ .layer(tower_http::trace::TraceLayer::new_for_http())+ .with_state(state);++ let listener = tokio::net::TcpListener::bind(&cli.listen).await?;+ tracing::info!(listen = cli.listen, "pgapi listening");+ axum::serve(listener, app).await?;+ Ok(())+}diff --git a/rust/pgapi/src/mcp.rs b/rust/pgapi/src/mcp.rsnew file mode 100644index 000000000000..f4b3dcd7456e--- /dev/null+++ b/rust/pgapi/src/mcp.rs@@ -0,0 +1,347 @@+//! MCP server (streamable HTTP at /mcp). Every tool is read-only and maps onto the+//! same `queries` functions the REST API uses. Auth happens in the axum middleware+//! before requests reach here; the principal is read back from the HTTP request+//! parts for audit logging.++use crate::config::Range;+use crate::queries as q;+use crate::AppState;+use rmcp::{+ handler::server::{router::tool::ToolRouter, wrapper::Parameters},+ model::*,+ schemars, tool, tool_handler, tool_router,+ transport::streamable_http_server::{+ session::local::LocalSessionManager, StreamableHttpServerConfig, StreamableHttpService,+ },+ ErrorData as McpError, ServerHandler,+};+use serde::Deserialize;+use std::sync::Arc;++#[derive(Clone)]+pub struct PgMcp {+ state: Arc<AppState>,+ #[allow(dead_code)] // referenced by the #[tool_handler] macro expansion+ tool_router: ToolRouter<Self>,+}++fn ok(v: serde_json::Value) -> Result<CallToolResult, McpError> {+ Ok(CallToolResult::success(vec![ContentBlock::text(+ serde_json::to_string_pretty(&v).unwrap_or_default(),+ )]))+}+fn err(e: anyhow::Error) -> McpError {+ McpError::internal_error(format!("{e:#}"), None)+}+fn range(+ since: &Option<String>,+) -> Result<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>), McpError> {+ Range {+ since: since.clone(),+ from: None,+ to: None,+ }+ .resolve()+ .map_err(err)+}++#[derive(Deserialize, schemars::JsonSchema)]+pub struct ServerArg {+ /// Server id as listed by list_servers (e.g. "cloud", "persons").+ pub server: String,+ /// Look-back window such as "15m", "1h", "24h". Default 1h.+ pub since: Option<String>,+}+#[derive(Deserialize, schemars::JsonSchema)]+pub struct TopQueriesArg {+ pub server: String,+ pub since: Option<String>,+ /// Restrict to one database.+ pub datname: Option<String>,+ /// One of total_exec_time (default), calls, mean_exec_time, rows, shared_blks_read, wal_bytes, storage_blks_read.+ pub order: Option<String>,+ pub limit: Option<i64>,+}+#[derive(Deserialize, schemars::JsonSchema)]+pub struct QueryArg {+ pub server: String,+ pub queryid: i64,+ pub since: Option<String>,+}+#[derive(Deserialize, schemars::JsonSchema)]+pub struct DbArg {+ pub server: String,+ pub datname: String,+ pub since: Option<String>,+ pub limit: Option<i64>,+}+#[derive(Deserialize, schemars::JsonSchema)]+pub struct OptDbArg {+ pub server: String,+ pub datname: Option<String>,+ pub since: Option<String>,+}+#[derive(Deserialize, schemars::JsonSchema)]+pub struct EventsArg {+ pub server: String,+ pub since: Option<String>,+ /// SQL LIKE pattern on event kind, e.g. "schema_%", "log_deadlock", "settings_changed".+ pub kind: Option<String>,+ pub limit: Option<i64>,+}+#[derive(Deserialize, schemars::JsonSchema)]+pub struct SchemaArg {+ pub server: String,+ pub datname: String,+ /// Restrict to one table.+ pub relname: Option<String>,+}+#[derive(Deserialize, schemars::JsonSchema)]+pub struct SettingsArg {+ pub server: String,+ /// Only settings whose source isn't 'default'.+ pub non_default_only: Option<bool>,+}+#[derive(Deserialize, schemars::JsonSchema)]+pub struct SqlArg {+ /// A single read-only SELECT/WITH statement against the stats database. Call describe_stats_schema first for table shapes.+ pub sql: String,+ pub limit: Option<i64>,+}++#[tool_router]+impl PgMcp {+ pub fn new(state: Arc<AppState>) -> Self {+ Self {+ state,+ tool_router: Self::tool_router(),+ }+ }++ #[tool(+ description = "List monitored Postgres servers (Aurora clusters) with version, instances, databases and collector freshness."+ )]+ async fn list_servers(&self) -> Result<CallToolResult, McpError> {+ ok(q::servers(&self.state.db).await.map_err(err)?)+ }++ #[tool(+ description = "Health overview of one server over a window: per-database throughput and cache hit, connection states, top wait events, event counts, top queries by time, tables needing vacuum."+ )]+ async fn server_overview(+ &self,+ Parameters(a): Parameters<ServerArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::overview(&self.state.db, &a.server, f, t)+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "Top queries by total time / calls / mean time / rows / I/O over a window, with normalized text, exact mean and stddev, and share of total time."+ )]+ async fn top_queries(+ &self,+ Parameters(a): Parameters<TopQueriesArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::top_queries(+ &self.state.db,+ &a.server,+ f,+ t,+ a.datname.as_deref(),+ a.order.as_deref().unwrap_or("total_exec_time"),+ a.limit.unwrap_or(25).clamp(1, 200),+ )+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "Everything about one query id: text, per-minute series, latency percentiles from sampled logs (p50/p90/p95/p99), slowest samples, execution plans (Aurora plan stats and auto_explain), wait events."+ )]+ async fn query_detail(+ &self,+ Parameters(a): Parameters<QueryArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::query_detail(&self.state.db, &a.server, a.queryid, f, t)+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "Wait-event breakdown over time (average active sessions by wait event, sampled every 10s) plus exact Aurora wait counts/times when available."+ )]+ async fn wait_events(+ &self,+ Parameters(a): Parameters<ServerArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::wait_events(&self.state.db, &a.server, f, t, "1m")+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "What is happening right now: connection counts by state, long-running / lock-waiting / idle-in-transaction sessions, blocking graph, memory-hungry backends."+ )]+ async fn current_activity(+ &self,+ Parameters(a): Parameters<ServerArg>,+ ) -> Result<CallToolResult, McpError> {+ ok(q::current_activity(&self.state.db, &a.server)+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "Per-table statistics for a database: live/dead tuples, scans, tuple churn, sizes, xid age, last vacuum/analyze."+ )]+ async fn table_stats(+ &self,+ Parameters(a): Parameters<DbArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::tables(+ &self.state.db,+ &a.server,+ &a.datname,+ f,+ t,+ a.limit.unwrap_or(100).clamp(1, 2000),+ )+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "Index definitions with usage over the window; flags indexes with zero scans (excluding unique/primary) as unused_in_range."+ )]+ async fn index_stats(+ &self,+ Parameters(a): Parameters<DbArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::indexes(&self.state.db, &a.server, &a.datname, f, t)+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "Vacuum health: tables past their autovacuum thresholds (dead tuples, analyze, xid/mxid freeze ratios), recent autovacuum runs from the log, vacuums in progress, database xid age."+ )]+ async fn vacuum_status(+ &self,+ Parameters(a): Parameters<OptDbArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(+ q::vacuum(&self.state.db, &a.server, a.datname.as_deref(), f, t)+ .await+ .map_err(err)?,+ )+ }+ #[tool(+ description = "Events: schema changes, setting changes, deadlocks, lock waits, statement cancellations, stats resets — with before/after details."+ )]+ async fn events(+ &self,+ Parameters(a): Parameters<EventsArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::events(+ &self.state.db,+ &a.server,+ f,+ t,+ a.kind.as_deref(),+ a.limit.unwrap_or(100).clamp(1, 1000),+ )+ .await+ .map_err(err)?)+ }+ #[tool(description = "Postgres settings (GUCs) on a server, optionally only non-default ones.")]+ async fn settings(+ &self,+ Parameters(a): Parameters<SettingsArg>,+ ) -> Result<CallToolResult, McpError> {+ ok(q::settings(+ &self.state.db,+ &a.server,+ a.non_default_only.unwrap_or(true),+ )+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "Schema of a database (or one table): columns, partitioning, indexes with definitions, constraints."+ )]+ async fn schema(+ &self,+ Parameters(a): Parameters<SchemaArg>,+ ) -> Result<CallToolResult, McpError> {+ ok(+ q::schema(&self.state.db, &a.server, &a.datname, a.relname.as_deref())+ .await+ .map_err(err)?,+ )+ }+ #[tool(+ description = "Errors and log activity over the window: grouped error summary, recent errors with statements, log counts by class, largest temp-file spills."+ )]+ async fn log_errors(+ &self,+ Parameters(a): Parameters<ServerArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::log_errors(&self.state.db, &a.server, f, t, 100)+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "System view: host CPU/memory (pg_proctab), top backends by CPU, checkpoints, bgwriter, Aurora replica status and per-database commit/DML latency."+ )]+ async fn system_stats(+ &self,+ Parameters(a): Parameters<ServerArg>,+ ) -> Result<CallToolResult, McpError> {+ let (f, t) = range(&a.since)?;+ ok(q::system(&self.state.db, &a.server, f, t)+ .await+ .map_err(err)?)+ }+ #[tool(+ description = "Is the collector itself healthy: ticks, errors and durations per collector/server in the last 15 minutes."+ )]+ async fn collector_health(&self) -> Result<CallToolResult, McpError> {+ ok(q::collector_health(&self.state.db).await.map_err(err)?)+ }+ #[tool(description = "Tables and columns of the stats database, for use with query_stats_db.")]+ async fn describe_stats_schema(&self) -> Result<CallToolResult, McpError> {+ ok(q::schema_of_stats_db(&self.state.db).await.map_err(err)?)+ }+ #[tool(+ description = "Run a read-only SQL query directly against the stats database (partitioned ts_* time series keyed by server_id/instance/datname/collected_at, cur_* current state, events). Use when the other tools don't answer the question."+ )]+ async fn query_stats_db(+ &self,+ Parameters(a): Parameters<SqlArg>,+ ) -> Result<CallToolResult, McpError> {+ ok(q::raw_sql(&self.state.db, &a.sql, a.limit.unwrap_or(200))+ .await+ .map_err(err)?)+ }+}++#[tool_handler]+impl ServerHandler for PgMcp {+ fn get_info(&self) -> ServerInfo {+ ServerInfo::new(ServerCapabilities::builder().enable_tools().build())+ .with_server_info(Implementation::from_build_env())+ .with_instructions("Read-only access to PostHog's Postgres telemetry (pgcollector). Start with list_servers, then server_overview; drill into top_queries / query_detail for performance, current_activity for live issues, vacuum_status and events for maintenance. query_stats_db runs arbitrary read-only SQL against the stats database.")+ }+}++pub fn service(state: Arc<AppState>) -> StreamableHttpService<PgMcp, LocalSessionManager> {+ StreamableHttpService::new(+ move || Ok(PgMcp::new(state.clone())),+ LocalSessionManager::default().into(),+ StreamableHttpServerConfig::default(),+ )+}diff --git a/rust/pgapi/src/queries.rs b/rust/pgapi/src/queries.rsnew file mode 100644index 000000000000..ca23c85471fe--- /dev/null+++ b/rust/pgapi/src/queries.rs@@ -0,0 +1,440 @@+//! The data layer: every question the REST API and the MCP tools can answer, as+//! functions over the stats DB returning JSON. Keep SQL here so both surfaces stay+//! in lock-step and the API layer is thin.++use crate::db::Db;+use anyhow::Result;+use chrono::{DateTime, Utc};+use serde_json::{json, Value};++type Ts = DateTime<Utc>;++/// Query a table that may not exist yet (created on first data by the collector).+async fn opt(+ db: &Db,+ sql: &str,+ params: &[&(dyn tokio_postgres::types::ToSql + Sync)],+) -> Result<Vec<Value>> {+ match db.query(sql, params).await {+ Ok(v) => Ok(v),+ Err(e)+ if format!("{e:#}").contains("42P01")+ || format!("{e:#}").contains("does not exist") =>+ {+ Ok(vec![])+ }+ Err(e) => Err(e),+ }+}++pub async fn servers(db: &Db) -> Result<Value> {+ let rows = db.query(+ "SELECT s.server_id, s.version, s.version_num, s.aurora_version, s.instances, s.databases, s.first_seen, s.last_seen,+ (SELECT max(started_at) FROM collector_runs r WHERE r.server_id = s.server_id) AS last_collected_at,+ (SELECT count(*) FROM collector_runs r WHERE r.server_id = s.server_id AND r.started_at > now() - interval '10 minutes' AND r.error IS NOT NULL)::bigint AS errors_10m+ FROM cur_servers s ORDER BY s.server_id", &[]).await?;+ Ok(json!(rows))+}++pub async fn overview(db: &Db, server: &str, from: Ts, to: Ts) -> Result<Value> {+ let dbs = opt(db, "SELECT datname, instance,+ sum(xact_commit)::bigint AS xact_commit, sum(xact_rollback)::bigint AS xact_rollback,+ sum(blks_hit)::bigint AS blks_hit, sum(blks_read)::bigint AS blks_read,+ CASE WHEN sum(blks_hit + blks_read) > 0 THEN round((sum(blks_hit)::numeric / sum(blks_hit + blks_read)) * 100, 2)::float8 END AS cache_hit_pct,+ sum(tup_inserted)::bigint AS tup_inserted, sum(tup_updated)::bigint AS tup_updated, sum(tup_deleted)::bigint AS tup_deleted,+ sum(deadlocks)::bigint AS deadlocks, sum(temp_files)::bigint AS temp_files, sum(temp_bytes)::bigint AS temp_bytes,+ max(xid_age)::bigint AS xid_age, max(numbackends)::bigint AS max_backends+ FROM ts_database_stats WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3+ GROUP BY 1, 2 ORDER BY 1, 2", &[&server, &from, &to]).await?;+ let conns = opt(db, "SELECT instance, state, sum(backends)::bigint AS backends+ FROM ts_activity_samples WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2)+ GROUP BY 1, 2 ORDER BY 1, 2", &[&server, &from]).await?;+ let waits = opt(db, "SELECT wait_event_type, wait_event, sum(backends)::bigint AS samples+ FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND state = 'active'+ GROUP BY 1, 2 ORDER BY 3 DESC LIMIT 15", &[&server, &from, &to]).await?;+ let events = opt(db, "SELECT kind, count(*)::bigint AS n FROM events WHERE server_id = $1 AND at >= $2 AND at < $3 GROUP BY 1 ORDER BY 2 DESC", &[&server, &from, &to]).await?;+ let top = top_queries(db, server, from, to, None, "total_exec_time", 5).await?;+ let vac = opt(db, "SELECT datname, relname, round(vacuum_ratio::numeric, 2)::float8 AS vacuum_ratio, round(freeze_ratio::numeric, 3)::float8 AS freeze_ratio, autovacuum_enabled+ FROM ts_vacuum_needed WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_vacuum_needed WHERE server_id = $1 AND collected_at >= $2)+ AND (vacuum_ratio >= 1 OR freeze_ratio >= 0.5) ORDER BY greatest(vacuum_ratio, freeze_ratio * 2) DESC LIMIT 10", &[&server, &from]).await?;+ Ok(+ json!({ "server_id": server, "from": from, "to": to, "databases": dbs, "connections": conns, "top_wait_events": waits, "events": events, "top_queries": top, "vacuum_attention": vac }),+ )+}++pub async fn top_queries(+ db: &Db,+ server: &str,+ from: Ts,+ to: Ts,+ datname: Option<&str>,+ order: &str,+ limit: i64,+) -> Result<Value> {+ let order_col = match order {+ "calls" => "calls",+ "mean_exec_time" => "mean_ms",+ "rows" => "rows",+ "shared_blks_read" => "shared_blks_read",+ "wal_bytes" => "wal_bytes",+ "storage_blks_read" => "storage_blks_read",+ _ => "total_ms",+ };+ let sql = format!(+ "WITH agg AS (+ SELECT s.queryid, s.datname, s.rolname,+ sum(s.calls)::bigint AS calls, sum(s.total_exec_time)::float8 AS total_ms, sum(s.rows)::bigint AS rows,+ CASE WHEN sum(s.calls) > 0 THEN sum(s.total_exec_time) / sum(s.calls) END::float8 AS mean_ms,+ CASE WHEN sum(s.calls) > 0 THEN sqrt(greatest(sum(s.sumsq_exec_time) / sum(s.calls) - power(sum(s.total_exec_time) / sum(s.calls), 2), 0)) END::float8 AS stddev_ms,+ sum(s.shared_blks_hit)::bigint AS shared_blks_hit, sum(s.shared_blks_read)::bigint AS shared_blks_read,+ sum(s.temp_blks_written)::bigint AS temp_blks_written, sum(s.wal_bytes)::bigint AS wal_bytes,+ sum(s.blk_read_time)::float8 AS blk_read_ms,+ {aurora}+ count(DISTINCT s.instance)::bigint AS instances+ FROM ts_query_stats s+ WHERE s.server_id = $1 AND s.collected_at >= $2 AND s.collected_at < $3 AND ($4::text IS NULL OR s.datname = $4)+ GROUP BY 1, 2, 3)+ SELECT a.*, q.query, q.fingerprint,+ round((a.total_ms / nullif(sum(a.total_ms) OVER (), 0) * 100)::numeric, 2)::float8 AS pct_of_total_time+ FROM agg a LEFT JOIN cur_queries q ON q.server_id = $1 AND q.queryid = a.queryid AND q.datname = a.datname+ ORDER BY {order_col} DESC NULLS LAST LIMIT $5",+ aurora = if has_column(db, "ts_query_stats", "storage_blks_read").await { "sum(s.storage_blks_read)::bigint AS storage_blks_read, max(s.max_exec_peakmem)::bigint AS max_exec_peakmem," } else { "NULL::bigint AS storage_blks_read, NULL::bigint AS max_exec_peakmem," },+ );+ Ok(json!(+ opt(db, &sql, &[&server, &from, &to, &datname, &limit]).await?+ ))+}++async fn has_column(db: &Db, table: &str, col: &str) -> bool {+ db.query(+ "SELECT 1 FROM information_schema.columns WHERE table_name = $1 AND column_name = $2",+ &[&table, &col],+ )+ .await+ .map(|r| !r.is_empty())+ .unwrap_or(false)+}++pub async fn query_detail(db: &Db, server: &str, queryid: i64, from: Ts, to: Ts) -> Result<Value> {+ let texts = opt(db, "SELECT datname, query, fingerprint, truncated, first_seen, last_seen FROM cur_queries WHERE server_id = $1 AND queryid = $2", &[&server, &queryid]).await?;+ let fingerprint: Option<i64> = texts.first().and_then(|t| t["fingerprint"].as_i64());+ let series = opt(db, "SELECT date_trunc('minute', collected_at) AS minute, instance, datname,+ sum(calls)::bigint AS calls, sum(total_exec_time)::float8 AS total_ms,+ CASE WHEN sum(calls) > 0 THEN sum(total_exec_time) / sum(calls) END::float8 AS mean_ms,+ sum(rows)::bigint AS rows, sum(shared_blks_read)::bigint AS shared_blks_read, sum(shared_blks_hit)::bigint AS shared_blks_hit+ FROM ts_query_stats WHERE server_id = $1 AND queryid = $2 AND collected_at >= $3 AND collected_at < $4+ GROUP BY 1, 2, 3 ORDER BY 1", &[&server, &queryid, &from, &to]).await?;+ let quantiles = opt(db, "SELECT count(*)::bigint AS samples,+ percentile_cont(0.5) WITHIN GROUP (ORDER BY duration_ms)::float8 AS p50,+ percentile_cont(0.9) WITHIN GROUP (ORDER BY duration_ms)::float8 AS p90,+ percentile_cont(0.95) WITHIN GROUP (ORDER BY duration_ms)::float8 AS p95,+ percentile_cont(0.99) WITHIN GROUP (ORDER BY duration_ms)::float8 AS p99,+ max(duration_ms)::float8 AS max_ms, min(log_time) AS first_sample, max(log_time) AS last_sample+ FROM ts_query_durations WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4+ AND (query_id = $2 OR ($5::bigint IS NOT NULL AND fingerprint = $5))", &[&server, &queryid, &from, &to, &fingerprint]).await?;+ let slow_samples = opt(db, "SELECT log_time, log_stream, datname, usename, duration_ms, left(query, 500) AS query+ FROM ts_query_durations WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4+ AND (query_id = $2 OR ($5::bigint IS NOT NULL AND fingerprint = $5)) ORDER BY duration_ms DESC LIMIT 10", &[&server, &queryid, &from, &to, &fingerprint]).await?;+ let aurora_plans = opt(db, "SELECT p.planid, p.plan_type, p.plan_captured_time, p.explain_plan,+ (SELECT sum(calls) FROM ts_aurora_plans a WHERE a.server_id = $1 AND a.planid = p.planid AND a.queryid = $2 AND a.collected_at >= $3 AND a.collected_at < $4)::bigint AS calls,+ (SELECT sum(total_exec_time) FROM ts_aurora_plans a WHERE a.server_id = $1 AND a.planid = p.planid AND a.queryid = $2 AND a.collected_at >= $3 AND a.collected_at < $4)::float8 AS total_ms+ FROM cur_query_plans p WHERE p.server_id = $1 AND p.queryid = $2 ORDER BY calls DESC NULLS LAST", &[&server, &queryid, &from, &to]).await?;+ let logged_plans = opt(db, "SELECT log_time, datname, duration_ms, plan FROM ts_log_plans WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4+ AND (query_id = $2 OR ($5::bigint IS NOT NULL AND fingerprint = $5)) ORDER BY duration_ms DESC LIMIT 5", &[&server, &queryid, &from, &to, &fingerprint]).await?;+ let waits = opt(db, "SELECT wait_event_type, wait_event, sum(backends)::bigint AS samples FROM ts_activity_samples+ WHERE server_id = $1 AND query_id = $2 AND collected_at >= $3 AND collected_at < $4 GROUP BY 1, 2 ORDER BY 3 DESC LIMIT 10", &[&server, &queryid, &from, &to]).await?;+ Ok(+ json!({ "queryid": queryid, "texts": texts, "series": series, "latency_from_logs": quantiles.into_iter().next(), "slowest_samples": slow_samples,+ "plans": aurora_plans, "logged_plans": logged_plans, "wait_events": waits }),+ )+}++pub async fn wait_events(db: &Db, server: &str, from: Ts, to: Ts, bucket: &str) -> Result<Value> {+ let b = match bucket {+ "10s" => "10 seconds",+ "5m" => "5 minutes",+ "1h" => "1 hour",+ _ => "1 minute",+ };+ let sql = format!("SELECT to_timestamp(floor(extract(epoch FROM collected_at) / extract(epoch FROM interval '{b}')) * extract(epoch FROM interval '{b}')) AS bucket,+ instance, coalesce(wait_event_type, 'CPU') AS wait_event_type, coalesce(wait_event, 'CPU') AS wait_event,+ round(avg(backends)::numeric, 2)::float8 AS avg_active_sessions+ FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND state = 'active'+ GROUP BY 1, 2, 3, 4 ORDER BY 1");+ let sampled = opt(db, &sql, &[&server, &from, &to]).await?;+ let measured = opt(db, "SELECT instance, type_name, event_name, sum(waits)::bigint AS waits, sum(wait_time)::bigint AS wait_time_us+ FROM ts_aurora_system_waits WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2, 3 ORDER BY 5 DESC LIMIT 30", &[&server, &from, &to]).await?;+ Ok(json!({ "sampled": sampled, "measured_aurora": measured }))+}++pub async fn current_activity(db: &Db, server: &str) -> Result<Value> {+ let sessions = opt(db, "SELECT * FROM ts_activity_sessions WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_activity_sessions WHERE server_id = $1 AND collected_at > now() - interval '5 minutes') ORDER BY query_age_s DESC NULLS LAST", &[&server]).await?;+ let locks = opt(db, "SELECT * FROM ts_lock_waits WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_lock_waits WHERE server_id = $1 AND collected_at > now() - interval '5 minutes') ORDER BY waiting_s DESC", &[&server]).await?;+ let counts = opt(db, "SELECT instance, datname, state, sum(backends)::bigint AS backends FROM ts_activity_samples WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_activity_samples WHERE server_id = $1 AND collected_at > now() - interval '5 minutes') GROUP BY 1, 2, 3 ORDER BY 1, 2, 3", &[&server]).await?;+ let memctx = opt(db, "SELECT * FROM ts_aurora_memctx WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_aurora_memctx WHERE server_id = $1 AND collected_at > now() - interval '5 minutes') ORDER BY allocated_bytes DESC LIMIT 20", &[&server]).await?;+ Ok(+ json!({ "connections": counts, "sessions": sessions, "lock_waits": locks, "memory_hogs": memctx }),+ )+}++pub async fn tables(+ db: &Db,+ server: &str,+ datname: &str,+ from: Ts,+ to: Ts,+ limit: i64,+) -> Result<Value> {+ let rows = opt(db, "WITH stats AS (+ SELECT schemaname, relname, sum(seq_scan)::bigint AS seq_scan, sum(seq_tup_read)::bigint AS seq_tup_read, sum(idx_scan)::bigint AS idx_scan,+ sum(n_tup_ins)::bigint AS n_tup_ins, sum(n_tup_upd)::bigint AS n_tup_upd, sum(n_tup_del)::bigint AS n_tup_del, sum(n_tup_hot_upd)::bigint AS n_tup_hot_upd,+ sum(heap_blks_read)::bigint AS heap_blks_read, sum(heap_blks_hit)::bigint AS heap_blks_hit,+ sum(vacuum_count + autovacuum_count)::bigint AS vacuums, sum(analyze_count + autoanalyze_count)::bigint AS analyzes+ FROM ts_table_stats WHERE server_id = $1 AND datname = $2 AND collected_at >= $3 AND collected_at < $4 GROUP BY 1, 2),+ latest AS (+ SELECT schemaname, relname, n_live_tup, n_dead_tup, n_mod_since_analyze, xid_age, reltuples, last_autovacuum, last_autoanalyze+ FROM ts_table_stats WHERE server_id = $1 AND datname = $2 AND collected_at = (SELECT max(collected_at) FROM ts_table_stats WHERE server_id = $1 AND datname = $2 AND collected_at >= $3)),+ sizes AS (+ SELECT schemaname, relname, heap_bytes, index_bytes, toast_bytes, total_bytes+ FROM ts_sizes WHERE server_id = $1 AND datname = $2 AND collected_at = (SELECT max(collected_at) FROM ts_sizes WHERE server_id = $1 AND datname = $2 AND collected_at >= $3))+ SELECT coalesce(l.schemaname, s.schemaname, z.schemaname) AS schemaname, coalesce(l.relname, s.relname, z.relname) AS relname,+ l.n_live_tup, l.n_dead_tup, l.n_mod_since_analyze, l.xid_age, l.last_autovacuum, l.last_autoanalyze,+ s.seq_scan, s.seq_tup_read, s.idx_scan, s.n_tup_ins, s.n_tup_upd, s.n_tup_del, s.n_tup_hot_upd, s.heap_blks_read, s.heap_blks_hit, s.vacuums, s.analyzes,+ z.heap_bytes, z.index_bytes, z.toast_bytes, z.total_bytes+ FROM latest l FULL JOIN stats s USING (schemaname, relname) FULL JOIN sizes z USING (schemaname, relname)+ ORDER BY z.total_bytes DESC NULLS LAST LIMIT $5", &[&server, &datname, &from, &to, &limit]).await?;+ Ok(json!(rows))+}++pub async fn indexes(db: &Db, server: &str, datname: &str, from: Ts, to: Ts) -> Result<Value> {+ let rows = opt(db, "WITH stats AS (+ SELECT schemaname, relname, indexrelname, sum(idx_scan)::bigint AS idx_scan, sum(idx_tup_read)::bigint AS idx_tup_read, sum(idx_blks_read)::bigint AS idx_blks_read+ FROM ts_index_stats WHERE server_id = $1 AND datname = $2 AND collected_at >= $3 AND collected_at < $4 GROUP BY 1, 2, 3)+ SELECT d.schemaname, d.relname, d.indexname, d.definition, d.is_unique, d.is_primary, d.is_valid, d.access_method, d.columns,+ coalesce(s.idx_scan, 0) AS idx_scan, s.idx_tup_read, s.idx_blks_read,+ (coalesce(s.idx_scan, 0) = 0 AND NOT d.is_unique AND NOT d.is_primary) AS unused_in_range+ FROM cur_schema_indexes d LEFT JOIN stats s ON s.schemaname = d.schemaname AND s.relname = d.relname AND s.indexrelname = d.indexname+ WHERE d.server_id = $1 AND d.datname = $2 AND d.last_seen > now() - interval '3 hours'+ ORDER BY unused_in_range DESC, idx_scan ASC", &[&server, &datname, &from, &to]).await?;+ Ok(json!(rows))+}++pub async fn vacuum(+ db: &Db,+ server: &str,+ datname: Option<&str>,+ from: Ts,+ to: Ts,+) -> Result<Value> {+ let needed = opt(db, "SELECT * FROM ts_vacuum_needed WHERE server_id = $1 AND ($2::text IS NULL OR datname = $2)+ AND collected_at = (SELECT max(collected_at) FROM ts_vacuum_needed WHERE server_id = $1 AND collected_at >= $3)+ ORDER BY greatest(vacuum_ratio, analyze_ratio, freeze_ratio * 2) DESC", &[&server, &datname, &from]).await?;+ let runs = opt(db, "SELECT log_time, log_stream, kind, relation, aggressive, index_scans, pages_removed, pages_remain, tuples_removed, tuples_remain, tuples_dead_not_removable,+ buffer_hits, buffer_misses, wal_bytes, read_mb_s, write_mb_s, elapsed_s+ FROM ts_autovacuum_runs WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4 AND ($2::text IS NULL OR relation LIKE $2 || '.%')+ ORDER BY log_time DESC LIMIT 100", &[&server, &datname, &from, &to]).await?;+ let progress = opt(db, "SELECT * FROM ts_vacuum_progress WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_vacuum_progress WHERE server_id = $1 AND collected_at > now() - interval '5 minutes')", &[&server]).await?;+ let xid = opt(db, "SELECT datname, max(xid_age)::bigint AS xid_age FROM ts_database_stats WHERE server_id = $1 AND collected_at >= $2 GROUP BY 1 ORDER BY 2 DESC", &[&server, &from]).await?;+ Ok(+ json!({ "needed": needed, "recent_runs": runs, "in_progress": progress, "database_xid_age": xid }),+ )+}++pub async fn events(+ db: &Db,+ server: &str,+ from: Ts,+ to: Ts,+ kind: Option<&str>,+ limit: i64,+) -> Result<Value> {+ Ok(json!(opt(db, "SELECT id, at, instance, datname, kind, subject, before, after FROM events WHERE server_id = $1 AND at >= $2 AND at < $3 AND ($4::text IS NULL OR kind LIKE $4)+ ORDER BY at DESC LIMIT $5", &[&server, &from, &to, &kind, &limit]).await?))+}++pub async fn settings(db: &Db, server: &str, non_default_only: bool) -> Result<Value> {+ Ok(json!(opt(db, "SELECT instance, name, setting, unit, source, boot_val, pending_restart, category FROM cur_settings WHERE server_id = $1 AND ($2 = false OR source <> 'default') ORDER BY name", &[&server, &non_default_only]).await?))+}++pub async fn schema(db: &Db, server: &str, datname: &str, relname: Option<&str>) -> Result<Value> {+ let rels = opt(db, "SELECT schemaname, relname, relkind, parent, partition_key, partition_bound, n_columns, columns, reloptions, view_definition, first_seen, last_seen+ FROM cur_schema_relations WHERE server_id = $1 AND datname = $2 AND ($3::text IS NULL OR relname = $3) AND last_seen > now() - interval '3 hours' ORDER BY 1, 2", &[&server, &datname, &relname]).await?;+ let idx = opt(db, "SELECT schemaname, relname, indexname, definition, is_unique, is_primary, is_valid, is_partial, columns FROM cur_schema_indexes WHERE server_id = $1 AND datname = $2 AND ($3::text IS NULL OR relname = $3) AND last_seen > now() - interval '3 hours' ORDER BY 1, 2, 3", &[&server, &datname, &relname]).await?;+ let cons = opt(db, "SELECT schemaname, relname, conname, contype, definition, is_validated, referenced_table FROM cur_schema_constraints WHERE server_id = $1 AND datname = $2 AND ($3::text IS NULL OR relname = $3) AND last_seen > now() - interval '3 hours' ORDER BY 1, 2, 3", &[&server, &datname, &relname]).await?;+ Ok(json!({ "relations": rels, "indexes": idx, "constraints": cons }))+}++pub async fn log_errors(db: &Db, server: &str, from: Ts, to: Ts, limit: i64) -> Result<Value> {+ let errors = opt(db, "SELECT log_time, log_stream, level, class, sqlstate, datname, usename, pid, query_id, message, detail, statement FROM ts_log_errors+ WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY log_time DESC LIMIT $4", &[&server, &from, &to, &limit]).await?;+ let summary = opt(db, "SELECT class, sqlstate, left(message, 120) AS message, count(*)::bigint AS n FROM ts_log_errors+ WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2, 3 ORDER BY 4 DESC LIMIT 20", &[&server, &from, &to]).await?;+ let counts = opt(db, "SELECT level, class, sum(count)::bigint AS n FROM ts_logs WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2 ORDER BY 3 DESC", &[&server, &from, &to]).await?;+ let temp = opt(db, "SELECT log_time, datname, usename, query_id, size_bytes, left(statement, 300) AS statement FROM ts_temp_files WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY size_bytes DESC LIMIT 20", &[&server, &from, &to]).await?;+ Ok(json!({ "summary": summary, "counts": counts, "recent": errors, "temp_files": temp }))+}++pub async fn system(db: &Db, server: &str, from: Ts, to: Ts) -> Result<Value> {+ let cpu = opt(db, "SELECT collected_at, instance,+ round(((user_jiffies + nice_jiffies + system_jiffies + iowait_jiffies)::numeric / nullif(user_jiffies + nice_jiffies + system_jiffies + iowait_jiffies + idle_jiffies, 0)) * 100, 2)::float8 AS cpu_pct,+ round((iowait_jiffies::numeric / nullif(user_jiffies + nice_jiffies + system_jiffies + iowait_jiffies + idle_jiffies, 0)) * 100, 2)::float8 AS iowait_pct+ FROM ts_system_cpu WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY 1", &[&server, &from, &to]).await?;+ let mem = opt(db, "SELECT collected_at, instance, mem_used_kb, mem_free_kb, mem_cached_kb, swap_used_kb, load1, load5 FROM ts_system_memory WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY 1", &[&server, &from, &to]).await?;+ let backends = opt(db, "SELECT instance, datname, usename, application_name, backend_type, sum(utime_jiffies + stime_jiffies)::bigint AS cpu_jiffies, max(rss_kb)::bigint AS max_rss_kb+ FROM ts_backend_cpu WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2, 3, 4, 5 ORDER BY 6 DESC LIMIT 20", &[&server, &from, &to]).await?;+ let checkpoints = opt(db, "SELECT log_time, log_stream, kind, buffers_written, buffers_pct, write_s, sync_s, total_s, distance_kb FROM ts_checkpoints WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY log_time DESC LIMIT 50", &[&server, &from, &to]).await?;+ let bgw = opt(db, "SELECT instance, sum(checkpoints_timed)::bigint AS checkpoints_timed, sum(checkpoints_req)::bigint AS checkpoints_req, sum(buffers_checkpoint)::bigint AS buffers_checkpoint, sum(buffers_clean)::bigint AS buffers_clean, sum(buffers_alloc)::bigint AS buffers_alloc+ FROM ts_bgwriter WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1", &[&server, &from, &to]).await?;+ let repl = opt(db, "SELECT * FROM ts_aurora_replica_status WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_aurora_replica_status WHERE server_id = $1 AND collected_at >= $2)", &[&server, &from]).await?;+ let latency = opt(db, "SELECT datname, sum(commit_latency_us)::bigint AS commit_latency_us, sum(select_count)::bigint AS selects, sum(update_count)::bigint AS updates,+ CASE WHEN sum(update_count) > 0 THEN sum(update_latency_us) / sum(update_count) END::float8 AS avg_update_latency_us+ FROM ts_aurora_db_latency WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1", &[&server, &from, &to]).await?;+ Ok(+ json!({ "cpu": cpu, "memory": mem, "top_backends_by_cpu": backends, "checkpoints": checkpoints, "bgwriter": bgw, "aurora_replicas": repl, "aurora_db_latency": latency }),+ )+}++pub async fn collector_health(db: &Db) -> Result<Value> {+ Ok(json!(db.query("SELECT server_id, instance, collector, count(*)::bigint AS ticks, count(error)::bigint AS errors, round(avg(duration_ms))::bigint AS avg_ms, max(duration_ms)::bigint AS max_ms, max(started_at) AS last_tick,+ max(error) AS last_error+ FROM collector_runs WHERE started_at > now() - interval '15 minutes' GROUP BY 1, 2, 3 ORDER BY errors DESC, 1, 2, 3", &[]).await?))+}++/// Free-form read-only SQL against the stats DB for agents.+///+/// Defence in depth, because a leading `SELECT` does not make a statement side-effect+/// free (`pg_advisory_lock()`, `pg_sleep()`, `set_config()` are all callable from one):+/// * only a single SELECT / WITH / EXPLAIN statement is accepted;+/// * it runs inside a read-only transaction with its own short statement timeout;+/// * the session is `DISCARD ALL`ed afterwards (drops advisory locks, temp tables,+/// session settings) and, if that fails, thrown away rather than returned to the pool;+/// * the DB user is a read-only role with no privileges beyond SELECT.+pub async fn raw_sql(db: &Db, sql: &str, limit: i64) -> Result<Value> {+ let trimmed = sql.trim().trim_end_matches(';').trim();+ let head = trimmed+ .split_whitespace()+ .next()+ .unwrap_or("")+ .to_ascii_uppercase();+ anyhow::ensure!(+ matches!(head.as_str(), "SELECT" | "WITH" | "EXPLAIN"),+ "only SELECT / WITH / EXPLAIN statements are allowed"+ );+ anyhow::ensure!(!trimmed.contains(';'), "one statement only");+ if let Some(f) = denied_function(trimmed) {+ anyhow::bail!("function {f}() is not allowed here");+ }+ let statement = if head == "EXPLAIN" {+ // EXPLAIN cannot be wrapped in a subquery; it returns text rows itself.+ trimmed.to_string()+ } else {+ format!(+ "SELECT * FROM ({trimmed}) _q LIMIT {}",+ limit.clamp(1, 5000)+ )+ };+ db.query_isolated(&statement).await+}++/// Functions that have effects beyond returning rows and are therefore refused in raw+/// SQL even though the statement is a SELECT. Session isolation (`query_isolated`)+/// already contains most of these; the denylist makes the intent explicit and stops+/// the cheap ones (sleeping, signalling backends, resetting stats) before they run.+const DENIED_FUNCTIONS: &[&str] = &[+ "pg_sleep",+ "pg_sleep_for",+ "pg_sleep_until",+ "pg_advisory_lock",+ "pg_advisory_lock_shared",+ "pg_advisory_xact_lock",+ "pg_advisory_xact_lock_shared",+ "pg_try_advisory_lock",+ "pg_try_advisory_lock_shared",+ "pg_try_advisory_xact_lock",+ "pg_try_advisory_xact_lock_shared",+ "pg_advisory_unlock",+ "pg_advisory_unlock_all",+ "pg_terminate_backend",+ "pg_cancel_backend",+ "pg_reload_conf",+ "pg_rotate_logfile",+ "pg_stat_reset",+ "pg_stat_reset_shared",+ "pg_stat_reset_single_table_counters",+ "pg_stat_reset_single_function_counters",+ "pg_stat_statements_reset",+ "set_config",+ "pg_notify",+ "pg_switch_wal",+ "pg_create_restore_point",+ "pg_backup_start",+ "pg_backup_stop",+ "pg_start_backup",+ "pg_stop_backup",+ "pg_read_file",+ "pg_read_binary_file",+ "pg_ls_dir",+ "pg_stat_file",+ "lo_import",+ "lo_export",+ "lo_unlink",+ "dblink",+ "dblink_connect",+ "dblink_exec",+ "nextval",+ "setval",+ "txid_current",+ "pg_current_xact_id",+];++fn denied_function(sql: &str) -> Option<&'static str> {+ static COMMENT: once_cell::sync::Lazy<regex::Regex> =+ once_cell::sync::Lazy::new(|| regex::Regex::new(r"(?s)/\*.*?\*/|--[^\n]*").unwrap());+ static CALL: once_cell::sync::Lazy<regex::Regex> =+ once_cell::sync::Lazy::new(|| regex::Regex::new(r"(?i)\b([a-z_][a-z0-9_]*)\s*\(").unwrap());+ // Comments are legal between a function name and its parenthesis (`pg_sleep/**/(1)`),+ // so scan the statement with them removed.+ let stripped = COMMENT.replace_all(sql, " ");+ CALL.captures_iter(&stripped).find_map(|c| {+ let name = c[1].to_ascii_lowercase();+ DENIED_FUNCTIONS.iter().copied().find(|d| *d == name)+ })+}++pub async fn schema_of_stats_db(db: &Db) -> Result<Value> {+ Ok(json!(db.query("SELECT c.relname AS table_name, string_agg(a.attname || ' ' || format_type(a.atttypid, a.atttypmod), ', ' ORDER BY a.attnum) AS columns+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND c.relname !~ '_[0-9]{8}$' GROUP BY 1 ORDER BY 1", &[]).await?))+}++#[cfg(test)]+mod tests {+ use super::denied_function;++ #[test]+ fn denylist_catches_side_effecting_calls() {+ assert_eq!(denied_function("select pg_sleep(20)"), Some("pg_sleep"));+ assert_eq!(+ denied_function("select PG_Advisory_Lock (1)"),+ Some("pg_advisory_lock")+ );+ assert_eq!(+ denied_function("select set_config('x', 'y', false)"),+ Some("set_config")+ );+ assert_eq!(+ denied_function("select count(*), max(collected_at) from ts_query_stats"),+ None+ );+ assert_eq!(denied_function("select pg_sleepy from t"), None);+ assert_eq!(denied_function("select pg_sleep/**/(1)"), Some("pg_sleep"));+ assert_eq!(+ denied_function("select pg_sleep -- x\n(1)"),+ Some("pg_sleep")+ );+ assert_eq!(+ denied_function("select pg_catalog.pg_advisory_lock/* c */ (1)"),+ Some("pg_advisory_lock")+ );+ }+}diff --git a/rust/pgapi/src/ui.rs b/rust/pgapi/src/ui.rsnew file mode 100644index 000000000000..57a175cb3176--- /dev/null+++ b/rust/pgapi/src/ui.rs@@ -0,0 +1,14 @@+//! Embedded single-page UI, served at `/` behind the same identity middleware as+//! the API. It only ever calls `/api/v1/*`.++use axum::http::header;+use axum::response::{Html, IntoResponse, Response};++pub async fn index() -> Response {+ // The page changes with every deploy; never let a browser keep a stale copy.+ (+ [(header::CACHE_CONTROL, "no-cache")],+ Html(include_str!("ui/index.html")),+ )+ .into_response()+}diff --git a/rust/pgapi/src/ui/index.html b/rust/pgapi/src/ui/index.htmlnew file mode 100644index 000000000000..b63a313b26e6--- /dev/null+++ b/rust/pgapi/src/ui/index.html@@ -0,0 +1,447 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>pgcollector</title>+<style>+ :root {+ --bg: #14161a; --panel: #1c1f25; --panel2: #22262d; --border: #2c313a;+ --text: #e6e8eb; --muted: #8b93a1; --accent: #7aa2f7; --ok: #6cc38b; --warn: #e0af68; --error: #f7768e;+ --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; }+ body { background: var(--bg); color: var(--text); font: 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, sans-serif; display: flex; flex-direction: column; }+ a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; }+ header { display: flex; align-items: center; gap: 14px; padding: 10px 16px; border-bottom: 1px solid var(--border); background: var(--panel); }+ header .brand { font-weight: 700; letter-spacing: .3px; }+ header .brand span { color: var(--muted); font-weight: 400; margin-left: 6px; }+ header .spacer { flex: 1; }+ header .me { color: var(--muted); font-size: 12px; }+ select, input, button { background: var(--panel2); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 5px 9px; font-size: 12px; font-family: inherit; }+ button { cursor: pointer; } button:hover { border-color: var(--accent); }+ .layout { display: flex; flex: 1; min-height: 0; }+ nav { width: 170px; flex: 0 0 170px; border-right: 1px solid var(--border); padding: 10px 0; background: var(--panel); overflow-y: auto; }+ nav a { display: block; padding: 7px 16px; color: var(--muted); } nav a.active { color: var(--text); background: var(--panel2); border-right: 2px solid var(--accent); }+ nav .group { padding: 10px 16px 4px; font-size: 10px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); }+ main { flex: 1; overflow: auto; padding: 16px 20px; }+ h1 { font-size: 16px; margin: 0 0 12px; } h1 .sub { color: var(--muted); font-weight: 400; font-size: 12px; margin-left: 8px; }+ .toolbar { display: flex; gap: 8px; align-items: center; margin: 0 0 12px; flex-wrap: wrap; }+ .grid { display: grid; gap: 12px; } .grid.two { grid-template-columns: 1fr 1fr; } .grid.tiles { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }+ .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px; min-width: 0; }+ .panel h2 { margin: 0 0 8px; font-size: 11px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); }+ .tile .v { font-size: 20px; font-weight: 600; font-family: var(--mono); } .tile .l { color: var(--muted); font-size: 11px; }+ table { width: 100%; border-collapse: collapse; font-size: 12px; }+ th, td { text-align: left; padding: 5px 8px; border-bottom: 1px solid var(--border); vertical-align: top; }+ th { color: var(--muted); font-weight: 500; white-space: nowrap; cursor: pointer; user-select: none; } th.sorted { color: var(--text); }+ td.num, th.num { text-align: right; font-family: var(--mono); white-space: nowrap; }+ td.mono { font-family: var(--mono); } .muted { color: var(--muted); } .ok { color: var(--ok); } .warn { color: var(--warn); } .err { color: var(--error); }+ .q { font-family: var(--mono); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 520px; display: block; }+ .grid.two .q { max-width: 300px; }+ pre { background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 10px; font-family: var(--mono); font-size: 11.5px; overflow: auto; white-space: pre-wrap; word-break: break-word; margin: 0; max-height: 420px; }+ .error-box { padding: 10px 14px; color: var(--error); font-family: var(--mono); font-size: 12px; white-space: pre-wrap; border: 1px solid var(--error); border-radius: 6px; }+ .empty { color: var(--muted); padding: 8px 0; }+ .bar { display: inline-block; height: 8px; background: var(--accent); border-radius: 2px; vertical-align: middle; }+ svg.chart { width: 100%; height: 140px; display: block; }+ .legend { display: flex; gap: 12px; font-size: 11px; color: var(--muted); margin-top: 4px; }+ .legend i { display: inline-block; width: 10px; height: 3px; margin-right: 4px; vertical-align: middle; }+ .kv td:first-child { color: var(--muted); width: 180px; }+ .pill { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 11px; background: var(--panel2); border: 1px solid var(--border); }+ .clickable { cursor: pointer; } tr.clickable:hover td { background: var(--panel2); }+ details summary { cursor: pointer; color: var(--muted); }+</style>+</head>+<body>+<header>+ <div class="brand">pgcollector<span>Postgres telemetry</span></div>+ <label>server <select id="server"></select></label>+ <label>range <select id="range">+ <option value="15m">15m</option><option value="1h" selected>1h</option><option value="6h">6h</option><option value="24h">24h</option><option value="7d">7d</option>+ </select></label>+ <button id="refresh" title="reload">↻</button>+ <div class="spacer"></div>+ <div class="me" id="me"></div>+</header>+<div class="layout">+ <nav id="nav"></nav>+ <main id="main"></main>+</div>+<script>+(() => {+ // ---------- state & routing ----------+ const PAGES = [+ ['overview', 'Overview'], ['queries', 'Queries'], ['activity', 'Activity'], ['waits', 'Wait events'],+ ['tables', 'Tables'], ['indexes', 'Indexes'], ['vacuum', 'Vacuum'], ['events', 'Events'], ['logs', 'Logs'],+ ['system', 'System'], ['schema', 'Schema'], ['settings', 'Settings'], ['collector', 'Collector health'],+ ];+ const state = { servers: [], server: null, page: 'overview', params: {}, range: '1h' };+ const $ = (s, r = document) => r.querySelector(s);+ const el = (tag, attrs = {}, ...kids) => {+ const e = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) { if (k === 'class') e.className = v; else if (k.startsWith('on')) e.addEventListener(k.slice(2), v); else if (v != null) e.setAttribute(k, v); }+ for (const k of kids.flat()) if (k != null) e.append(k.nodeType ? k : document.createTextNode(String(k)));+ return e;+ };++ function parseHash() {+ const m = location.hash.match(/^#\/([^/]+)\/([^?]+)(?:\?(.*))?$/);+ if (!m) return null;+ return { server: decodeURIComponent(m[1]), page: m[2], params: Object.fromEntries(new URLSearchParams(m[3] || '')) };+ }+ function go(page, params = {}, server = state.server) {+ const qs = new URLSearchParams(params).toString();+ location.hash = `#/${encodeURIComponent(server)}/${page}${qs ? '?' + qs : ''}`;+ }++ // ---------- api & formatting ----------+ async function api(path, params = {}) {+ const qs = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null && v !== '')).toString();+ const r = await fetch(`/api/v1${path}${qs ? '?' + qs : ''}`, { headers: { accept: 'application/json' } });+ if (!r.ok) { let msg = `${r.status} ${r.statusText}`; try { msg += ': ' + (await r.json()).error; } catch {} throw new Error(msg); }+ return r.json();+ }+ const fmt = {+ num: v => v == null ? '–' : Number(v).toLocaleString(undefined, { maximumFractionDigits: 0 }),+ dec: (v, d = 2) => v == null ? '–' : Number(v).toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: 0 }),+ ms: v => v == null ? '–' : (v >= 1000 ? (v / 1000).toFixed(2) + ' s' : v >= 10 ? v.toFixed(1) + ' ms' : v.toFixed(3) + ' ms'),+ bytes: v => { if (v == null) return '–'; const u = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0; v = Number(v); while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; } return v.toFixed(i ? 1 : 0) + ' ' + u[i]; },+ pct: v => v == null ? '–' : Number(v).toFixed(1) + '%',+ ago: t => { if (!t) return '–'; const s = (Date.now() - new Date(t)) / 1000; if (s < 90) return Math.round(s) + 's ago'; if (s < 5400) return Math.round(s / 60) + 'm ago'; if (s < 172800) return Math.round(s / 3600) + 'h ago'; return Math.round(s / 86400) + 'd ago'; },+ ts: t => t ? new Date(t).toLocaleString(undefined, { hour12: false }) : '–',+ time: t => t ? new Date(t).toLocaleTimeString(undefined, { hour12: false }) : '–',+ ratio: v => v == null ? '–' : el('span', { class: v >= 1 ? 'err' : v >= 0.7 ? 'warn' : '' }, Number(v).toFixed(2)),+ };++ // ---------- generic table ----------+ // cols: [{key, label, fmt?, num?, sort?(row)->number, render?(row)->node, cls?}]+ function table(rows, cols, { sortKey, desc = true, onRow, empty = 'nothing in this range', limit } = {}) {+ if (!rows || !rows.length) return el('div', { class: 'empty' }, empty);+ let sk = sortKey, sd = desc;+ const wrap = el('div');+ const render = () => {+ const sorted = [...rows];+ if (sk) { const c = cols.find(c => c.key === sk); const get = c && c.sort ? c.sort : r => r[sk]; sorted.sort((a, b) => { const x = get(a), y = get(b); if (x == null) return 1; if (y == null) return -1; return (typeof x === 'number' ? x - y : String(x).localeCompare(String(y))) * (sd ? -1 : 1); }); }+ const shown = limit ? sorted.slice(0, limit) : sorted;+ const t = el('table', {},+ el('thead', {}, el('tr', {}, cols.map(c => el('th', { class: (c.num ? 'num ' : '') + (sk === c.key ? 'sorted' : ''), onclick: () => { if (sk === c.key) sd = !sd; else { sk = c.key; sd = true; } render(); } }, c.label, sk === c.key ? (sd ? ' ▾' : ' ▴') : '')))),+ el('tbody', {}, shown.map(r => el('tr', { class: onRow ? 'clickable' : '', onclick: onRow ? () => onRow(r) : null }, cols.map(c => {+ const v = c.render ? c.render(r) : c.fmt ? c.fmt(r[c.key], r) : r[c.key];+ return el('td', { class: (c.num ? 'num ' : '') + (c.cls || '') }, v == null ? el('span', { class: 'muted' }, '–') : v);+ })))));+ wrap.replaceChildren(...[t, limit && rows.length > limit ? el('div', { class: 'muted', style: 'padding:6px 8px' }, `showing ${limit} of ${rows.length}`) : null].filter(Boolean));+ };+ render();+ return wrap;+ }+ const panel = (title, ...kids) => el('div', { class: 'panel' }, title ? el('h2', {}, title) : null, ...kids);+ const tile = (label, value, cls = '') => el('div', { class: 'panel tile' }, el('div', { class: 'v ' + cls }, value ?? '–'), el('div', { class: 'l' }, label));+ const queryCell = q => el('span', { class: 'q', title: q || '' }, q || el('span', { class: 'muted' }, '(text not captured)'));++ // ---------- simple SVG line chart ----------+ // series: [{name, color, points: [[Date, number]]}]+ function chart(series, { yfmt = v => fmt.dec(v, 1) } = {}) {+ const W = 800, H = 140, P = { l: 48, r: 8, t: 8, b: 20 };+ const all = series.flatMap(s => s.points);+ if (!all.length) return el('div', { class: 'empty' }, 'no data points');+ const xs = all.map(p => +p[0]), ys = all.map(p => p[1]);+ const x0 = Math.min(...xs), x1 = Math.max(...xs) || x0 + 1, y1 = Math.max(...ys, 0) || 1;+ const X = x => P.l + (x - x0) / (x1 - x0 || 1) * (W - P.l - P.r), Y = y => H - P.b - (y / y1) * (H - P.t - P.b);+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ svg.setAttribute('viewBox', `0 0 ${W} ${H}`); svg.setAttribute('class', 'chart'); svg.setAttribute('preserveAspectRatio', 'none');+ const n = (tag, a) => { const e = document.createElementNS('http://www.w3.org/2000/svg', tag); for (const [k, v] of Object.entries(a)) e.setAttribute(k, v); return e; };+ for (let i = 0; i <= 3; i++) { const y = Y(y1 * i / 3); svg.append(n('line', { x1: P.l, x2: W - P.r, y1: y, y2: y, stroke: '#2c313a', 'stroke-width': 1 })); const t = n('text', { x: P.l - 4, y: y + 4, 'text-anchor': 'end', fill: '#8b93a1', 'font-size': 10 }); t.textContent = yfmt(y1 * i / 3); svg.append(t); }+ for (const [i, x] of [x0, (x0 + x1) / 2, x1].entries()) { const t = n('text', { x: X(x), y: H - 4, 'text-anchor': i === 0 ? 'start' : i === 1 ? 'middle' : 'end', fill: '#8b93a1', 'font-size': 10 }); t.textContent = fmt.time(new Date(x)); svg.append(t); }+ for (const s of series) {+ const pts = [...s.points].sort((a, b) => a[0] - b[0]);+ svg.append(n('path', { d: pts.map((p, i) => (i ? 'L' : 'M') + X(+p[0]).toFixed(1) + ' ' + Y(p[1]).toFixed(1)).join(' '), fill: 'none', stroke: s.color, 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' }));+ }+ return el('div', {}, svg, el('div', { class: 'legend' }, series.map(s => el('span', {}, el('i', { style: `background:${s.color}` }), s.name))));+ }+ const COLORS = ['#7aa2f7', '#6cc38b', '#e0af68', '#f7768e', '#bb9af7', '#7dcfff', '#ff9e64', '#9ece6a'];++ // ---------- pages ----------+ const pages = {};+ const sv = () => state.servers.find(s => s.server_id === state.server) || {};+ const dbSelect = (onchange) => { const dbs = sv().databases || []; const cur = state.params.datname || dbs[0] || ''; const s = el('select', { onchange: e => onchange(e.target.value) }, dbs.map(d => el('option', { value: d, selected: d === cur ? '' : null }, d))); return [s, cur]; };++ pages.overview = async () => {+ const d = await api(`/servers/${state.server}/overview`, { since: state.range });+ const conns = d.connections.reduce((a, c) => { a[c.state] = (a[c.state] || 0) + c.backends; return a; }, {});+ const dbs = d.databases;+ const sum = k => dbs.reduce((a, r) => a + (r[k] || 0), 0);+ const hit = (() => { const h = sum('blks_hit'), r = sum('blks_read'); return h + r ? h / (h + r) * 100 : null; })();+ return [+ el('h1', {}, state.server, el('span', { class: 'sub' }, `${sv().version || ''} · ${fmt.ago(sv().last_collected_at)}`)),+ el('div', { class: 'grid tiles' },+ tile('connections (active)', conns.active ?? 0), tile('connections (idle)', conns.idle ?? 0), tile('idle in transaction', conns['idle in transaction'] ?? 0),+ tile('commits', fmt.num(sum('xact_commit'))), tile('rollbacks', fmt.num(sum('xact_rollback'))), tile('cache hit', hit == null ? '–' : hit.toFixed(2) + '%', hit != null && hit < 95 ? 'warn' : ''),+ tile('deadlocks', fmt.num(sum('deadlocks')), sum('deadlocks') ? 'err' : ''), tile('temp bytes', fmt.bytes(sum('temp_bytes'))), tile('max xid age', fmt.num(Math.max(0, ...dbs.map(r => r.xid_age || 0)))),+ ),+ el('div', { class: 'grid two', style: 'margin-top:12px' },+ panel('Top queries by total time', table(d.top_queries, [+ { key: 'query', label: 'query', render: r => el('a', { href: `#/${state.server}/query?queryid=${r.queryid}` }, queryCell(r.query)) },+ { key: 'calls', label: 'calls', num: true, fmt: fmt.num }, { key: 'mean_ms', label: 'mean', num: true, fmt: fmt.ms }, { key: 'pct_of_total_time', label: '% time', num: true, fmt: fmt.pct },+ ])),+ panel('Top wait events (active sessions, sampled)', table(d.top_wait_events, [+ { key: 'wait_event_type', label: 'type', fmt: v => v || 'CPU' }, { key: 'wait_event', label: 'event', fmt: v => v || '–' }, { key: 'samples', label: 'samples', num: true, fmt: fmt.num },+ ])),+ panel('Databases', table(dbs, [+ { key: 'datname', label: 'database' }, { key: 'instance', label: 'instance' }, { key: 'xact_commit', label: 'commits', num: true, fmt: fmt.num }, { key: 'cache_hit_pct', label: 'cache hit', num: true, fmt: fmt.pct },+ { key: 'tup_inserted', label: 'ins', num: true, fmt: fmt.num }, { key: 'tup_updated', label: 'upd', num: true, fmt: fmt.num }, { key: 'tup_deleted', label: 'del', num: true, fmt: fmt.num }, { key: 'xid_age', label: 'xid age', num: true, fmt: fmt.num },+ ])),+ panel('Events in range', table(d.events, [{ key: 'kind', label: 'kind', render: r => el('a', { href: `#/${state.server}/events?kind=${encodeURIComponent(r.kind)}` }, r.kind) }, { key: 'n', label: 'count', num: true, fmt: fmt.num }])),+ panel('Vacuum attention', table(d.vacuum_attention, [+ { key: 'datname', label: 'db' }, { key: 'relname', label: 'table' }, { key: 'vacuum_ratio', label: 'dead / threshold', num: true, render: r => fmt.ratio(r.vacuum_ratio) }, { key: 'freeze_ratio', label: 'freeze', num: true, render: r => fmt.ratio(r.freeze_ratio) }, { key: 'autovacuum_enabled', label: 'autovac', fmt: v => v ? 'on' : el('span', { class: 'err' }, 'off') },+ ], { empty: 'no tables past 100% of their vacuum threshold' })),+ ),+ ];+ };++ pages.queries = async () => {+ const order = state.params.order || 'total_exec_time';+ const rows = await api(`/servers/${state.server}/queries`, { since: state.range, order, limit: 200, datname: state.params.datname });+ const orders = [['total_exec_time', 'total time'], ['calls', 'calls'], ['mean_exec_time', 'mean time'], ['rows', 'rows'], ['shared_blks_read', 'blocks read'], ['wal_bytes', 'WAL bytes'], ['storage_blks_read', 'Aurora storage reads']];+ const [dbsel] = dbSelect(v => go('queries', { ...state.params, datname: v }));+ dbsel.prepend(el('option', { value: '', selected: state.params.datname ? null : '' }, 'all databases'));+ return [+ el('h1', {}, 'Queries', el('span', { class: 'sub' }, 'pg_stat_statements, per-interval deltas summed over the range')),+ el('div', { class: 'toolbar' }, el('label', {}, 'order by ', el('select', { onchange: e => go('queries', { ...state.params, order: e.target.value }) }, orders.map(([v, l]) => el('option', { value: v, selected: v === order ? '' : null }, l)))), el('label', {}, 'database ', dbsel)),+ panel(null, table(rows, [+ { key: 'query', label: 'query', render: r => queryCell(r.query) },+ { key: 'datname', label: 'db' }, { key: 'rolname', label: 'role' },+ { key: 'calls', label: 'calls', num: true, fmt: fmt.num }, { key: 'total_ms', label: 'total', num: true, fmt: fmt.ms }, { key: 'mean_ms', label: 'mean', num: true, fmt: fmt.ms }, { key: 'stddev_ms', label: 'stddev', num: true, fmt: fmt.ms },+ { key: 'rows', label: 'rows', num: true, fmt: fmt.num }, { key: 'shared_blks_read', label: 'blks read', num: true, fmt: fmt.num }, { key: 'pct_of_total_time', label: '% time', num: true, render: r => el('span', {}, el('span', { class: 'bar', style: `width:${Math.min(100, r.pct_of_total_time || 0)}px` }), ' ', fmt.pct(r.pct_of_total_time)) },+ ], { onRow: r => go('query', { queryid: r.queryid }) })),+ ];+ };++ pages.query = async () => {+ const qid = state.params.queryid;+ const d = await api(`/servers/${state.server}/queries/${qid}`, { since: state.range });+ const t = d.texts[0] || {};+ const byMin = {};+ for (const r of d.series) { const k = r.minute; (byMin[k] ||= { calls: 0, total: 0 }); byMin[k].calls += r.calls || 0; byMin[k].total += r.total_ms || 0; }+ const pts = Object.entries(byMin).map(([m, v]) => [new Date(m), v]);+ const lat = d.latency_from_logs || {};+ return [+ el('h1', {}, 'Query ', el('span', { class: 'mono' }, qid), el('span', { class: 'sub' }, t.datname || '')),+ panel('Text', el('pre', {}, t.query || '(not captured yet)'), t.truncated ? el('div', { class: 'muted' }, 'truncated at 10 KB') : null),+ el('div', { class: 'grid two', style: 'margin-top:12px' },+ panel('Calls per minute', chart([{ name: 'calls', color: COLORS[0], points: pts.map(([m, v]) => [m, v.calls]) }], { yfmt: fmt.num })),+ panel('Mean time per minute', chart([{ name: 'mean ms', color: COLORS[2], points: pts.map(([m, v]) => [m, v.calls ? v.total / v.calls : 0]) }], { yfmt: v => fmt.ms(v) })),+ panel('Latency from sampled statement log', lat.samples ? el('div', { class: 'grid tiles' }, tile('samples', fmt.num(lat.samples)), tile('p50', fmt.ms(lat.p50)), tile('p90', fmt.ms(lat.p90)), tile('p95', fmt.ms(lat.p95)), tile('p99', fmt.ms(lat.p99)), tile('max', fmt.ms(lat.max_ms))) : el('div', { class: 'empty' }, 'no sampled durations in this range (needs log_min_duration_sample and the logs collector)')),+ panel('Wait events while running', table(d.wait_events, [{ key: 'wait_event_type', label: 'type', fmt: v => v || 'CPU' }, { key: 'wait_event', label: 'event', fmt: v => v || '–' }, { key: 'samples', label: 'samples', num: true, fmt: fmt.num }])),+ ),+ el('div', { style: 'margin-top:12px' }, panel('Slowest logged samples', table(d.slowest_samples, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'log_stream', label: 'instance' }, { key: 'usename', label: 'user' }, { key: 'duration_ms', label: 'duration', num: true, fmt: fmt.ms }, { key: 'query', label: 'statement', render: r => queryCell(r.query) }]))),+ el('div', { style: 'margin-top:12px' }, panel('Execution plans (Aurora plan stats)', d.plans.length ? d.plans.map(p => el('details', { open: '' }, el('summary', {}, `plan ${p.planid} · ${p.plan_type} · calls ${fmt.num(p.calls)} · total ${fmt.ms(p.total_ms)} · captured ${fmt.ago(p.plan_captured_time)}`), el('pre', {}, p.explain_plan || ''))) : el('div', { class: 'empty' }, 'no plans (aurora_stat_plans is Aurora-only)'))),+ el('div', { style: 'margin-top:12px' }, panel('auto_explain plans from the log', d.logged_plans.length ? d.logged_plans.map(p => el('details', {}, el('summary', {}, `${fmt.ts(p.log_time)} · ${fmt.ms(p.duration_ms)} · ${p.datname}`), el('pre', {}, JSON.stringify(p.plan, null, 2)))) : el('div', { class: 'empty' }, 'none in range'))),+ ];+ };++ pages.activity = async () => {+ const d = await api(`/servers/${state.server}/activity`);+ return [+ el('h1', {}, 'Activity', el('span', { class: 'sub' }, 'latest 10s sample')),+ el('div', { class: 'grid two' },+ panel('Connections by state', table(d.connections, [{ key: 'instance', label: 'instance' }, { key: 'datname', label: 'db' }, { key: 'state', label: 'state' }, { key: 'backends', label: 'backends', num: true, fmt: fmt.num }])),+ panel('Lock waits (blocking graph)', table(d.lock_waits, [{ key: 'waiter_pid', label: 'waiter', num: true }, { key: 'waiting_s', label: 'waiting', num: true, fmt: v => fmt.dec(v, 0) + ' s' }, { key: 'wanted_mode', label: 'mode' }, { key: 'relation', label: 'relation' }, { key: 'blocker_pid', label: 'blocker', num: true }, { key: 'blocker_state', label: 'blocker state' }, { key: 'blocker_query', label: 'blocker query', render: r => queryCell(r.blocker_query) }], { empty: 'nothing blocked' })),+ ),+ el('div', { style: 'margin-top:12px' }, panel('Long-running / waiting / idle-in-transaction sessions', table(d.sessions, [+ { key: 'pid', label: 'pid', num: true }, { key: 'instance', label: 'instance' }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'application_name', label: 'app' }, { key: 'state', label: 'state' },+ { key: 'wait_event_type', label: 'wait', fmt: (v, r) => v ? `${v}:${r.wait_event}` : 'CPU' }, { key: 'query_age_s', label: 'query age', num: true, fmt: v => fmt.dec(v, 0) + ' s' }, { key: 'xact_age_s', label: 'xact age', num: true, fmt: v => fmt.dec(v, 0) + ' s' }, { key: 'blocked_by', label: 'blocked by' },+ { key: 'query', label: 'query', render: r => queryCell(r.query) },+ ], { empty: 'no interesting sessions right now' }))),+ d.memory_hogs.length ? el('div', { style: 'margin-top:12px' }, panel('Backends over 64 MB (Aurora memory contexts)', table(d.memory_hogs, [{ key: 'pid', label: 'pid', num: true }, { key: 'usename', label: 'user' }, { key: 'allocated_bytes', label: 'allocated', num: true, fmt: fmt.bytes }, { key: 'top_context', label: 'largest context' }, { key: 'query', label: 'query', render: r => queryCell(r.query) }]))) : null,+ ];+ };++ pages.waits = async () => {+ const d = await api(`/servers/${state.server}/waits`, { since: state.range, bucket: state.range === '15m' ? '10s' : state.range === '7d' ? '1h' : state.range === '24h' ? '5m' : '1m' });+ const byEv = {};+ for (const r of d.sampled) { const k = `${r.wait_event_type}:${r.wait_event}`; (byEv[k] ||= []).push([new Date(r.bucket), r.avg_active_sessions]); }+ const top = Object.entries(byEv).map(([k, pts]) => [k, pts.reduce((a, p) => a + p[1], 0), pts]).sort((a, b) => b[1] - a[1]).slice(0, 8);+ return [+ el('h1', {}, 'Wait events', el('span', { class: 'sub' }, 'average active sessions by wait event (10s samples)')),+ panel('Top wait events over time', chart(top.map(([k, , pts], i) => ({ name: k, color: COLORS[i % COLORS.length], points: pts })), { yfmt: v => fmt.dec(v, 1) })),+ d.measured_aurora.length ? el('div', { style: 'margin-top:12px' }, panel('Measured wait time (Aurora, exact)', table(d.measured_aurora, [{ key: 'instance', label: 'instance' }, { key: 'type_name', label: 'type' }, { key: 'event_name', label: 'event' }, { key: 'waits', label: 'waits', num: true, fmt: fmt.num }, { key: 'wait_time_us', label: 'time', num: true, fmt: v => fmt.ms(v / 1000) }]))) : null,+ ];+ };++ pages.tables = async () => {+ const [dbsel, db] = dbSelect(v => go('tables', { datname: v }));+ if (!db) return [el('h1', {}, 'Tables'), el('div', { class: 'empty' }, 'no databases discovered yet')];+ const rows = await api(`/servers/${state.server}/tables`, { since: state.range, datname: db, limit: 500 });+ return [+ el('h1', {}, 'Tables', el('span', { class: 'sub' }, 'counters summed over the range; sizes and tuples latest')),+ el('div', { class: 'toolbar' }, el('label', {}, 'database ', dbsel)),+ panel(null, table(rows, [+ { key: 'relname', label: 'table', fmt: (v, r) => `${r.schemaname}.${v}`, cls: 'mono' }, { key: 'total_bytes', label: 'size', num: true, fmt: fmt.bytes }, { key: 'index_bytes', label: 'indexes', num: true, fmt: fmt.bytes },+ { key: 'n_live_tup', label: 'live', num: true, fmt: fmt.num }, { key: 'n_dead_tup', label: 'dead', num: true, fmt: fmt.num }, { key: 'seq_scan', label: 'seq scans', num: true, fmt: fmt.num }, { key: 'idx_scan', label: 'idx scans', num: true, fmt: fmt.num },+ { key: 'n_tup_ins', label: 'ins', num: true, fmt: fmt.num }, { key: 'n_tup_upd', label: 'upd', num: true, fmt: fmt.num }, { key: 'n_tup_del', label: 'del', num: true, fmt: fmt.num }, { key: 'xid_age', label: 'xid age', num: true, fmt: fmt.num }, { key: 'last_autovacuum', label: 'last autovac', fmt: fmt.ago },+ ], { sortKey: 'total_bytes', onRow: r => go('schema', { datname: db, relname: r.relname }) })),+ ];+ };++ pages.indexes = async () => {+ const [dbsel, db] = dbSelect(v => go('indexes', { datname: v }));+ if (!db) return [el('h1', {}, 'Indexes'), el('div', { class: 'empty' }, 'no databases discovered yet')];+ const rows = await api(`/servers/${state.server}/indexes`, { since: state.range, datname: db });+ return [+ el('h1', {}, 'Indexes', el('span', { class: 'sub' }, 'scans summed over the range; unused = zero scans and not unique/primary')),+ el('div', { class: 'toolbar' }, el('label', {}, 'database ', dbsel)),+ panel(null, table(rows, [+ { key: 'unused_in_range', label: '', render: r => r.unused_in_range ? el('span', { class: 'pill warn' }, 'unused') : (r.is_valid === false ? el('span', { class: 'pill err' }, 'invalid') : null) },+ { key: 'indexname', label: 'index', fmt: (v, r) => `${r.schemaname}.${r.relname} › ${v}`, cls: 'mono' }, { key: 'idx_scan', label: 'scans', num: true, fmt: fmt.num }, { key: 'idx_tup_read', label: 'tuples read', num: true, fmt: fmt.num },+ { key: 'columns', label: 'columns', cls: 'mono' }, { key: 'access_method', label: 'am' }, { key: 'definition', label: 'definition', render: r => queryCell(r.definition) },+ ], { sortKey: 'idx_scan', desc: false, empty: 'no index metadata yet (schema collector runs hourly)' })),+ ];+ };++ pages.vacuum = async () => {+ const d = await api(`/servers/${state.server}/vacuum`, { since: state.range, datname: state.params.datname });+ return [+ el('h1', {}, 'Vacuum', el('span', { class: 'sub' }, 'effective autovacuum thresholds per table (reloptions ⊕ GUCs)')),+ el('div', { class: 'grid two' },+ panel('Database xid age', table(d.database_xid_age, [{ key: 'datname', label: 'db' }, { key: 'xid_age', label: 'xid age', num: true, fmt: fmt.num }])),+ panel('In progress', table(d.in_progress, [{ key: 'datname', label: 'db' }, { key: 'phase', label: 'phase' }, { key: 'heap_blks_scanned', label: 'scanned', num: true, fmt: fmt.num }, { key: 'heap_blks_total', label: 'total', num: true, fmt: fmt.num }, { key: 'running_seconds', label: 'running', num: true, fmt: v => fmt.dec(v, 0) + ' s' }], { empty: 'no vacuum running' })),+ ),+ el('div', { style: 'margin-top:12px' }, panel('Tables over 50% of a threshold', table(d.needed, [+ { key: 'datname', label: 'db' }, { key: 'relname', label: 'table', fmt: (v, r) => `${r.schemaname}.${v}`, cls: 'mono' }, { key: 'autovacuum_enabled', label: 'autovac', fmt: v => v ? 'on' : el('span', { class: 'err' }, 'off') },+ { key: 'n_dead_tup', label: 'dead', num: true, fmt: fmt.num }, { key: 'vacuum_ratio', label: 'vacuum', num: true, render: r => fmt.ratio(r.vacuum_ratio) }, { key: 'analyze_ratio', label: 'analyze', num: true, render: r => fmt.ratio(r.analyze_ratio) }, { key: 'insert_ratio', label: 'insert', num: true, render: r => fmt.ratio(r.insert_ratio) },+ { key: 'freeze_ratio', label: 'freeze', num: true, render: r => fmt.ratio(r.freeze_ratio) }, { key: 'xid_age', label: 'xid age', num: true, fmt: fmt.num }, { key: 'last_autovacuum', label: 'last autovac', fmt: fmt.ago }, { key: 'last_autoanalyze', label: 'last analyze', fmt: fmt.ago },+ ], { sortKey: 'vacuum_ratio', empty: 'nothing near a threshold' }))),+ el('div', { style: 'margin-top:12px' }, panel('Recent autovacuum runs (from the log)', table(d.recent_runs, [+ { key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'kind', label: 'kind' }, { key: 'relation', label: 'relation', cls: 'mono' }, { key: 'aggressive', label: 'aggr', fmt: v => v ? 'yes' : '' }, { key: 'tuples_removed', label: 'removed', num: true, fmt: fmt.num }, { key: 'tuples_remain', label: 'remain', num: true, fmt: fmt.num }, { key: 'tuples_dead_not_removable', label: 'not removable', num: true, fmt: fmt.num }, { key: 'index_scans', label: 'idx scans', num: true }, { key: 'elapsed_s', label: 'elapsed', num: true, fmt: v => fmt.dec(v, 1) + ' s' },+ ], { empty: 'none in range (needs log_autovacuum_min_duration and the logs collector)' }))),+ ];+ };++ pages.events = async () => {+ const rows = await api(`/servers/${state.server}/events`, { since: state.range, kind: state.params.kind, limit: 500 });+ const kinds = ['', 'schema_%', 'settings_%', 'log_%', 'stats_reset', 'pgss_dealloc'];+ return [+ el('h1', {}, 'Events', el('span', { class: 'sub' }, 'schema and settings changes, deadlocks, lock waits, cancellations, stats resets')),+ el('div', { class: 'toolbar' }, el('label', {}, 'kind ', el('select', { onchange: e => go('events', { kind: e.target.value }) }, kinds.map(k => el('option', { value: k, selected: k === (state.params.kind || '') ? '' : null }, k || 'all'))))),+ panel(null, table(rows, [+ { key: 'at', label: 'time', fmt: fmt.ts }, { key: 'kind', label: 'kind', render: r => el('span', { class: 'pill' }, r.kind) }, { key: 'datname', label: 'db' }, { key: 'subject', label: 'subject', cls: 'mono' },+ { key: 'after', label: 'details', render: r => el('details', {}, el('summary', {}, summarize(r)), el('pre', {}, JSON.stringify({ before: r.before, after: r.after }, null, 2))) },+ ], { empty: 'no events in range' })),+ ];+ };+ function summarize(e) {+ const a = e.after || {}, b = e.before || {};+ if (e.kind === 'settings_changed') return `${b.setting} → ${a.setting}`;+ if (e.kind.startsWith('log_')) return (a.statement || a.reason || a.detail || '').slice(0, 120);+ const keys = Object.keys(a).filter(k => k !== 'columns');+ return keys.slice(0, 4).map(k => `${k}=${JSON.stringify(a[k])}`).join(' ').slice(0, 140) || 'details';+ }++ pages.logs = async () => {+ const d = await api(`/servers/${state.server}/logs`, { since: state.range, limit: 300 });+ return [+ el('h1', {}, 'Logs', el('span', { class: 'sub' }, 'errors, cancellations and temp files from the Postgres log')),+ el('div', { class: 'grid two' },+ panel('Log lines by class', table(d.counts, [{ key: 'level', label: 'level' }, { key: 'class', label: 'class' }, { key: 'n', label: 'lines', num: true, fmt: fmt.num }])),+ panel('Errors grouped', table(d.summary, [{ key: 'class', label: 'class' }, { key: 'sqlstate', label: 'sqlstate', cls: 'mono' }, { key: 'message', label: 'message' }, { key: 'n', label: 'count', num: true, fmt: fmt.num }])),+ ),+ el('div', { style: 'margin-top:12px' }, panel('Recent errors', table(d.recent, [+ { key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'level', label: 'level', render: r => el('span', { class: r.level === 'ERROR' ? 'warn' : 'err' }, r.level) }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'message', label: 'message' }, { key: 'statement', label: 'statement', render: r => queryCell(r.statement) },+ ], { empty: 'no errors in range' }))),+ el('div', { style: 'margin-top:12px' }, panel('Largest temp-file spills', table(d.temp_files, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'size_bytes', label: 'size', num: true, fmt: fmt.bytes }, { key: 'statement', label: 'statement', render: r => queryCell(r.statement) }], { empty: 'none (needs log_temp_files)' }))),+ ];+ };++ pages.system = async () => {+ const d = await api(`/servers/${state.server}/system`, { since: state.range });+ const byInst = (rows, key) => { const m = {}; for (const r of rows) (m[r.instance] ||= []).push([new Date(r.collected_at), r[key]]); return Object.entries(m).map(([n, pts], i) => ({ name: n, color: COLORS[i], points: pts })); };+ return [+ el('h1', {}, 'System'),+ el('div', { class: 'grid two' },+ panel('CPU % (pg_proctab)', d.cpu.length ? chart(byInst(d.cpu, 'cpu_pct'), { yfmt: fmt.pct }) : el('div', { class: 'empty' }, 'no pg_proctab data (CREATE EXTENSION pg_proctab)')),+ panel('Load average', d.memory.length ? chart(byInst(d.memory, 'load1'), { yfmt: v => fmt.dec(v, 2) }) : el('div', { class: 'empty' }, 'no pg_proctab data')),+ panel('Checkpoints (from the log)', table(d.checkpoints, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'kind', label: 'kind' }, { key: 'buffers_written', label: 'buffers', num: true, fmt: fmt.num }, { key: 'buffers_pct', label: '%', num: true, fmt: fmt.pct }, { key: 'write_s', label: 'write', num: true, fmt: v => fmt.dec(v, 2) + ' s' }, { key: 'sync_s', label: 'sync', num: true, fmt: v => fmt.dec(v, 2) + ' s' }, { key: 'distance_kb', label: 'distance', num: true, fmt: v => fmt.bytes(v * 1024) }], { empty: 'none in range' })),+ panel('bgwriter / checkpointer (summed)', table(d.bgwriter, [{ key: 'instance', label: 'instance' }, { key: 'checkpoints_timed', label: 'timed', num: true, fmt: fmt.num }, { key: 'checkpoints_req', label: 'requested', num: true, fmt: fmt.num }, { key: 'buffers_checkpoint', label: 'ckpt buffers', num: true, fmt: fmt.num }, { key: 'buffers_clean', label: 'bgw buffers', num: true, fmt: fmt.num }, { key: 'buffers_alloc', label: 'allocated', num: true, fmt: fmt.num }])),+ panel('Aurora replicas', table(d.aurora_replicas, [{ key: 'instance_id', label: 'instance' }, { key: 'role', label: 'role' }, { key: 'replica_lag_ms', label: 'lag', num: true, fmt: v => v == null ? '–' : fmt.ms(v) }, { key: 'replay_latency_us', label: 'replay', num: true, fmt: v => fmt.ms(v / 1000) }, { key: 'active_txns', label: 'txns', num: true }, { key: 'storage_daemon_cpu', label: 'storage cpu', num: true, fmt: fmt.pct }], { empty: 'not Aurora' })),+ panel('Aurora per-database latency', table(d.aurora_db_latency, [{ key: 'datname', label: 'db' }, { key: 'commit_latency_us', label: 'commit latency (sum)', num: true, fmt: v => fmt.ms(v / 1000) }, { key: 'selects', label: 'selects', num: true, fmt: fmt.num }, { key: 'updates', label: 'updates', num: true, fmt: fmt.num }, { key: 'avg_update_latency_us', label: 'avg update', num: true, fmt: v => fmt.ms(v / 1000) }], { empty: 'not Aurora' })),+ ),+ d.top_backends_by_cpu.length ? el('div', { style: 'margin-top:12px' }, panel('Top backends by CPU (pg_proctab)', table(d.top_backends_by_cpu, [{ key: 'instance', label: 'instance' }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'application_name', label: 'app' }, { key: 'backend_type', label: 'type' }, { key: 'cpu_jiffies', label: 'cpu jiffies', num: true, fmt: fmt.num }, { key: 'max_rss_kb', label: 'max rss', num: true, fmt: v => fmt.bytes(v * 1024) }]))) : null,+ ];+ };++ pages.schema = async () => {+ const [dbsel, db] = dbSelect(v => go('schema', { datname: v }));+ if (!db) return [el('h1', {}, 'Schema'), el('div', { class: 'empty' }, 'no databases discovered yet')];+ const d = await api(`/servers/${state.server}/schema`, { datname: db, relname: state.params.relname });+ const rel = state.params.relname;+ return [+ el('h1', {}, 'Schema', el('span', { class: 'sub' }, rel ? `${db} › ${rel}` : db)),+ el('div', { class: 'toolbar' }, el('label', {}, 'database ', dbsel), rel ? el('button', { onclick: () => go('schema', { datname: db }) }, '← all relations') : null),+ rel ? [+ panel('Columns', d.relations.length ? table(d.relations[0].columns || [], [{ key: 'name', label: 'column', cls: 'mono' }, { key: 'type', label: 'type', cls: 'mono' }, { key: 'notnull', label: 'not null', fmt: v => v ? 'yes' : '' }, { key: 'default', label: 'default', cls: 'mono' }]) : el('div', { class: 'empty' }, 'unknown relation')),+ el('div', { style: 'margin-top:12px' }, panel('Indexes', table(d.indexes, [{ key: 'indexname', label: 'index', cls: 'mono' }, { key: 'is_valid', label: 'valid', fmt: v => v ? 'yes' : el('span', { class: 'err' }, 'no') }, { key: 'definition', label: 'definition', cls: 'mono' }]))),+ el('div', { style: 'margin-top:12px' }, panel('Constraints', table(d.constraints, [{ key: 'conname', label: 'name', cls: 'mono' }, { key: 'contype', label: 'type' }, { key: 'definition', label: 'definition', cls: 'mono' }, { key: 'is_validated', label: 'validated', fmt: v => v ? 'yes' : el('span', { class: 'warn' }, 'no') }]))),+ ] : panel(null, table(d.relations, [+ { key: 'relname', label: 'relation', fmt: (v, r) => `${r.schemaname}.${v}`, cls: 'mono' }, { key: 'relkind', label: 'kind', fmt: v => ({ r: 'table', p: 'partitioned', v: 'view', m: 'matview' })[v] || v }, { key: 'parent', label: 'parent', cls: 'mono' }, { key: 'n_columns', label: 'cols', num: true }, { key: 'partition_key', label: 'partition key', cls: 'mono' }, { key: 'last_seen', label: 'seen', fmt: fmt.ago },+ ], { sortKey: 'relname', desc: false, onRow: r => go('schema', { datname: db, relname: r.relname }), empty: 'no schema snapshot yet (runs hourly)' })),+ ];+ };++ pages.settings = async () => {+ const all = state.params.all === '1';+ const rows = await api(`/servers/${state.server}/settings`, { non_default: !all });+ return [+ el('h1', {}, 'Settings'),+ el('div', { class: 'toolbar' }, el('label', {}, el('input', { type: 'checkbox', checked: all ? '' : null, onchange: e => go('settings', { all: e.target.checked ? '1' : '0' }) }), ' show defaults too')),+ panel(null, table(rows, [{ key: 'name', label: 'name', cls: 'mono' }, { key: 'setting', label: 'value', cls: 'mono' }, { key: 'unit', label: 'unit' }, { key: 'source', label: 'source' }, { key: 'category', label: 'category' }, { key: 'pending_restart', label: 'pending restart', fmt: v => v ? el('span', { class: 'warn' }, 'yes') : '' }], { sortKey: 'name', desc: false, empty: 'no settings snapshot yet (runs hourly)' })),+ ];+ };++ pages.collector = async () => {+ const rows = await api('/collector/health');+ return [+ el('h1', {}, 'Collector health', el('span', { class: 'sub' }, 'last 15 minutes, all servers')),+ panel(null, table(rows, [+ { key: 'server_id', label: 'server' }, { key: 'instance', label: 'instance' }, { key: 'collector', label: 'collector', cls: 'mono' }, { key: 'ticks', label: 'ticks', num: true }, { key: 'errors', label: 'errors', num: true, render: r => el('span', { class: r.errors ? 'err' : 'ok' }, r.errors) },+ { key: 'avg_ms', label: 'avg', num: true, fmt: fmt.ms }, { key: 'max_ms', label: 'max', num: true, fmt: fmt.ms }, { key: 'last_tick', label: 'last tick', fmt: fmt.ago }, { key: 'last_error', label: 'last error', render: r => r.last_error ? el('span', { class: 'q err', title: r.last_error }, r.last_error) : null },+ ], { sortKey: 'errors', empty: 'no collector runs recorded' })),+ ];+ };++ // ---------- shell ----------+ function renderNav() {+ $('#nav').replaceChildren(el('div', { class: 'group' }, 'server'), ...PAGES.map(([p, l]) => el('a', { href: `#/${encodeURIComponent(state.server)}/${p}`, class: state.page === p || (p === 'queries' && state.page === 'query') ? 'active' : '' }, l)));+ }+ async function render() {+ const main = $('#main');+ const fn = pages[state.page];+ if (!fn) { main.replaceChildren(el('div', { class: 'error-box' }, `unknown page ${state.page}`)); return; }+ main.replaceChildren(el('div', { class: 'muted' }, 'loading…'));+ try { const out = await fn(); main.replaceChildren(...[out].flat(Infinity).filter(Boolean)); }+ catch (e) { main.replaceChildren(el('div', { class: 'error-box' }, String(e.message || e))); }+ }+ async function route() {+ const h = parseHash();+ if (!h && state.servers.length) { go('overview', {}, state.servers[0].server_id); return; }+ if (h) { state.server = h.server; state.page = h.page; state.params = h.params; }+ $('#server').value = state.server;+ renderNav();+ render();+ }+ async function boot() {+ try { const me = await api('/me'); $('#me').textContent = `${me.email} · ${me.source}`; } catch (e) { $('#me').textContent = 'unauthenticated'; }+ try { state.servers = await api('/servers'); } catch (e) { $('#main').replaceChildren(el('div', { class: 'error-box' }, String(e.message))); return; }+ const sel = $('#server');+ sel.replaceChildren(...state.servers.map(s => el('option', { value: s.server_id }, `${s.server_id}${s.errors_10m ? ' ⚠' : ''}`)));+ sel.onchange = () => go(state.page === 'query' ? 'queries' : state.page, {}, sel.value);+ $('#range').onchange = e => { state.range = e.target.value; render(); };+ $('#refresh').onclick = render;+ window.addEventListener('hashchange', route);+ if (!state.servers.length) { $('#main').replaceChildren(el('div', { class: 'empty' }, 'no servers registered yet — is the collector running?')); return; }+ route();+ }+ boot();+})();+</script>+</body>+</html>diff --git a/rust/pgapi/values.example.yaml b/rust/pgapi/values.example.yamlnew file mode 100644index 000000000000..deb25c85dc21--- /dev/null+++ b/rust/pgapi/values.example.yaml@@ -0,0 +1,89 @@+# Golden-chart (charts/posthog-app) values for pgapi — the API + MCP server over the+# pgcollector stats DB. Copy to charts/apps/pgapi/values.yaml (+ values.<env>.yaml).+#+# Auth model (no OAuth in the app; identity comes from the edge):+# browsers → ingress.internal: true → ALB + Cognito; app verifies x-amzn-oidc-data (ES256)+# MCP/CLI → tailscaleIngress + whois → Tailscale-User-Login, trusted only because the+# NetworkPolicy below admits nothing but the operator's proxy pods+# Then authorisation: @posthog.com only (PGAPI_ALLOWED_DOMAINS). Everything is read-only.++image:+ name: pgapi+ repository: 795637471508.dkr.ecr.us-east-1.amazonaws.com/pgcollector # same image as the collector++command: ["/pgapi"]++autoscaling:+ minPods: 1+ maxPods: 2+resources:+ requests: { cpu: 250m, memory: 256Mi }+ limits: { cpu: 250m, memory: 512Mi }++service:+ port: 3400+ targetPort: 3400+livenessProbe:+ httpGet: { path: /healthz, port: 3400 }+readinessProbe:+ httpGet: { path: /readyz, port: 3400 }+monitoring:+ prometheus:+ path: /metrics+ port: "3400"++# --- browser path: Cognito-gated internal host -------------------------------+ingress:+ enabled: true+ internal: true+ defaultRoute: true+ # host: pgapi.prod-us.posthog.dev # per env in values.<env>.yaml+ timeoutPolicy:+ idle: 1h # MCP streams stay open++# --- MCP / CLI path: tailnet host with identity headers -----------------------+tailscaleIngress:+ enabled: true+ # host: pgapi-prod-us # per env; MagicDNS name → https://pgapi-prod-us.<tailnet>.ts.net/mcp+ tags: "tag:pgapi" # engineering-only ACL, see docs/deploy.md+ whois: true++# whois makes Tailscale-User-Login a credential: only the Tailscale operator's proxy+# pods and the internal ingress Envoy may reach the container port.+networkPolicy:+ enabled: true+ allowFrom:+ - podSelector:+ tailscale.com/managed: "true"+ namespaceSelector:+ kubernetes.io/metadata.name: tailscale+ ports:+ - port: 3400+ protocol: TCP+ - podSelector: {}+ namespaceSelector:+ kubernetes.io/metadata.name: contour # the internal-ingress Envoy namespace+ ports:+ - port: 3400+ protocol: TCP++env:+ PGAPI_LISTEN: "0.0.0.0:3400"+ PGAPI_TRUST_TAILSCALE: "1"+ # PGAPI_TAILSCALE_HOSTS: pgapi-prod-us.hedgehog-kitefin.ts.net # default: any *.ts.net host+ # Both required together to enable the Cognito/ALB path:+ PGAPI_ALB_REGION: us-east-1+ PGAPI_ALB_CLIENT_ID: 7d7earg8ande8rgp1coal63rva # Cognito app client for the env (charts/argocd/ingress/values)+ # PGAPI_ALB_ARN: arn:aws:elasticloadbalancing:us-east-1:<account>:loadbalancer/app/<internal-alb>/<id> # tokens from any other ALB are rejected+ PGAPI_ALLOWED_DOMAINS: posthog.com+ # PGAPI_ALLOWED_HOSTS: pgapi.prod-us.posthog.dev,pgapi-prod-us.hedgehog-kitefin.ts.net # DNS-rebinding guard+ RUST_LOG: info++# Read-only user on the stats DB (users_readonly tier).+psql:+ pgcollector:+ pgbouncer: false+ read:+ enabled: true+ env:+ PGAPI_DATABASE_URL: POSTGRES_URL