Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Add ClickHouse stats endpoints and integrate Database component in Ad… (#828)

Goldflagaca59588e369
diff --git a/client/messages/cs.json b/client/messages/cs.json
index cee8e4639..a6f53a2e9 100644
--- a/client/messages/cs.json
+++ b/client/messages/cs.json
@@ -195,8 +195,8 @@
"Zx7WPP": "Všechny řady událostí skryty",
"AKRVhS": "Klikni na položku v legendě pro zobrazení",
"NuhCPH": "Zjisti, jak sledovat události",
- "/aq5/F": "Žádné vlastní události nenalezeny",
"ES6IYH": "Zkus jiný časový rozsah nebo filtr",
+ "/aq5/F": "Žádné vlastní události nenalezeny",
"j7BiRg": "Žádná událost nevybrána.",
"kF9XUo": "Časové razítko",
"EwRIOm": "Uživatel",
@@ -597,8 +597,8 @@
"zINlao": "Vlastník",
"iHN12u": "Administrátor",
"7L86Z5": "Člen",
- "Nvr5Ce": "Přidávám...",
"v+BwPW": "Přidat do organizace",
+ "Nvr5Ce": "Přidávám...",
"Msn3jj": "Filtrovat podle emailu...",
"gO9HzB": "Filtrovat podle role",
"9nrF+x": "Všechny role",
@@ -613,8 +613,6 @@
"J2wna+": "Odebrat uživatele z organizace?",
"rDEYPT": "Vyber organizaci, ze které chceš odebrat {email}. Ztratí přístup ke všem zdrojům v dané organizaci.",
"3Vr8ps": "Administrátorský panel",
- "OpgSlo": "Administrátorské nastavení",
- "LaqXuS": "Panel nastavení bude brzy k dispozici...",
"KI5ndC": "Neplatný formát domény. Musí být platná doména jako example.com nebo sub.example.com",
"cGNlRB": "Upgraduj na Pro pro přidání více webů",
"UpxSPM": "Pro přidání webů musíš mít aktivní předplatné",
diff --git a/client/messages/de.json b/client/messages/de.json
index d0c242efc..bbb6ff3ae 100644
--- a/client/messages/de.json
+++ b/client/messages/de.json
@@ -195,8 +195,8 @@
"Zx7WPP": "Alle Event-Reihen ausgeblendet",
"AKRVhS": "Klicken Sie auf ein Legendenelement, um es anzuzeigen",
"NuhCPH": "Erfahren Sie, wie Sie Events verfolgen",
- "/aq5/F": "Keine benutzerdefinierten Events gefunden",
"ES6IYH": "Versuchen Sie einen anderen Zeitraum oder Filter",
+ "/aq5/F": "Keine benutzerdefinierten Events gefunden",
"j7BiRg": "Kein Event ausgewählt.",
"kF9XUo": "Zeitstempel",
"EwRIOm": "Benutzer",
@@ -597,8 +597,8 @@
"zINlao": "Inhaber",
"iHN12u": "Administrator",
"7L86Z5": "Mitglied",
- "Nvr5Ce": "Wird hinzugefügt...",
"v+BwPW": "Zur Organisation hinzufügen",
+ "Nvr5Ce": "Wird hinzugefügt...",
"Msn3jj": "Nach E-Mail filtern...",
"gO9HzB": "Nach Rolle filtern",
"9nrF+x": "Alle Rollen",
@@ -613,8 +613,6 @@
"J2wna+": "Benutzer aus Organisation entfernen?",
"rDEYPT": "Wählen Sie die Organisation, aus der {email} entfernt werden soll. Der Zugriff auf alle Ressourcen dieser Organisation geht verloren.",
"3Vr8ps": "Admin-Dashboard",
- "OpgSlo": "Admin-Einstellungen",
- "LaqXuS": "Einstellungsbereich kommt bald...",
"KI5ndC": "Ungültiges Domainformat. Muss eine gültige Domain wie beispiel.de oder sub.beispiel.de sein",
"cGNlRB": "Upgrade auf Pro, um weitere Websites hinzuzufügen",
"UpxSPM": "Sie benötigen ein aktives Abonnement, um Websites hinzuzufügen",
diff --git a/client/messages/en.json b/client/messages/en.json
index 3b126f152..c72982d66 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -613,8 +613,6 @@
"J2wna+": "Remove user from organization?",
"rDEYPT": "Select the organization to remove {email} from. They will lose access to all resources in that organization.",
"3Vr8ps": "Admin Dashboard",
- "OpgSlo": "Admin Settings",
- "LaqXuS": "Settings panel coming soon...",
"KI5ndC": "Invalid domain format. Must be a valid domain like example.com or sub.example.com",
"cGNlRB": "Upgrade to Pro to add more websites",
"UpxSPM": "You need to be on an active subscription to add websites",
diff --git a/client/messages/es.json b/client/messages/es.json
index 0f8c0ba6a..ef1717a72 100644
--- a/client/messages/es.json
+++ b/client/messages/es.json
@@ -195,8 +195,8 @@
"Zx7WPP": "Todas las series de eventos ocultas",
"AKRVhS": "Haz clic en un elemento de la leyenda para mostrarlo",
"NuhCPH": "Aprende cómo rastrear eventos",
- "/aq5/F": "No se encontraron eventos personalizados",
"ES6IYH": "Prueba un rango de fechas o filtro diferente",
+ "/aq5/F": "No se encontraron eventos personalizados",
"j7BiRg": "Ningún evento seleccionado.",
"kF9XUo": "Marca de tiempo",
"EwRIOm": "Usuario",
@@ -597,8 +597,8 @@
"zINlao": "Propietario",
"iHN12u": "Administrador",
"7L86Z5": "Miembro",
- "Nvr5Ce": "Añadiendo...",
"v+BwPW": "Añadir a la organización",
+ "Nvr5Ce": "Añadiendo...",
"Msn3jj": "Filtrar por correo electrónico...",
"gO9HzB": "Filtrar por rol",
"9nrF+x": "Todos los roles",
@@ -613,8 +613,6 @@
"J2wna+": "¿Eliminar usuario de la organización?",
"rDEYPT": "Selecciona la organización de la que eliminar a {email}. Perderán acceso a todos los recursos en esa organización.",
"3Vr8ps": "Panel de administración",
- "OpgSlo": "Configuraciones de administración",
- "LaqXuS": "Panel de configuración próximamente...",
"KI5ndC": "Formato de dominio no válido. Debe ser un dominio válido como example.com o sub.example.com",
"cGNlRB": "Actualiza a Pro para añadir más sitios web",
"UpxSPM": "Necesitas tener una suscripción activa para añadir sitios web",
diff --git a/client/messages/fr.json b/client/messages/fr.json
index ee0cf895d..ea3a42034 100644
--- a/client/messages/fr.json
+++ b/client/messages/fr.json
@@ -195,8 +195,8 @@
"Zx7WPP": "Toutes les séries d'événements masquées",
"AKRVhS": "Cliquez sur un élément de la légende pour l'afficher",
"NuhCPH": "Apprenez à suivre les événements",
- "/aq5/F": "Aucun événement personnalisé trouvé",
"ES6IYH": "Essayez une autre période ou un autre filtre",
+ "/aq5/F": "Aucun événement personnalisé trouvé",
"j7BiRg": "Aucun événement sélectionné.",
"kF9XUo": "Horodatage",
"EwRIOm": "Utilisateur",
@@ -597,8 +597,8 @@
"zINlao": "Propriétaire",
"iHN12u": "Administrateur",
"7L86Z5": "Membre",
- "Nvr5Ce": "Ajout en cours...",
"v+BwPW": "Ajouter à l'organisation",
+ "Nvr5Ce": "Ajout en cours...",
"Msn3jj": "Filtrer par e-mail...",
"gO9HzB": "Filtrer par rôle",
"9nrF+x": "Tous les rôles",
@@ -613,8 +613,6 @@
"J2wna+": "Retirer l'utilisateur de l'organisation ?",
"rDEYPT": "Sélectionnez l'organisation d'où retirer {email}. L'accès à toutes les ressources de cette organisation sera perdu.",
"3Vr8ps": "Tableau de bord admin",
- "OpgSlo": "Paramètres admin",
- "LaqXuS": "Panneau de paramètres bientôt disponible...",
"KI5ndC": "Format de domaine invalide. Doit être un domaine valide comme exemple.com ou sub.exemple.com",
"cGNlRB": "Passez à Pro pour ajouter plus de sites web",
"UpxSPM": "Vous devez avoir un abonnement actif pour ajouter des sites web",
diff --git a/client/messages/it.json b/client/messages/it.json
index c59ce4147..940cdbeac 100644
--- a/client/messages/it.json
+++ b/client/messages/it.json
@@ -195,8 +195,8 @@
"Zx7WPP": "Tutte le serie di eventi nascoste",
"AKRVhS": "Clicca un elemento della legenda per mostrarlo",
"NuhCPH": "Scopri come tracciare gli eventi",
- "/aq5/F": "Nessun evento personalizzato trovato",
"ES6IYH": "Prova un intervallo di date diverso o un filtro",
+ "/aq5/F": "Nessun evento personalizzato trovato",
"j7BiRg": "Nessun evento selezionato.",
"kF9XUo": "Timestamp",
"EwRIOm": "Utente",
@@ -597,8 +597,8 @@
"zINlao": "Proprietario",
"iHN12u": "Amministratore",
"7L86Z5": "Membro",
- "Nvr5Ce": "Aggiunta in corso...",
"v+BwPW": "Aggiungi all'Organizzazione",
+ "Nvr5Ce": "Aggiunta in corso...",
"Msn3jj": "Filtra per email...",
"gO9HzB": "Filtra per ruolo",
"9nrF+x": "Tutti i Ruoli",
@@ -613,8 +613,6 @@
"J2wna+": "Rimuovere l'utente dall'organizzazione?",
"rDEYPT": "Seleziona l'organizzazione da cui rimuovere {email}. Perderà l'accesso a tutte le risorse in quell'organizzazione.",
"3Vr8ps": "Dashboard Amministratore",
- "OpgSlo": "Impostazioni Amministratore",
- "LaqXuS": "Pannello impostazioni in arrivo...",
"KI5ndC": "Formato dominio non valido. Deve essere un dominio valido come example.com o sub.example.com",
"cGNlRB": "Passa a Pro per aggiungere più siti web",
"UpxSPM": "Devi avere un abbonamento attivo per aggiungere siti web",
diff --git a/client/messages/ja.json b/client/messages/ja.json
index ef3d0ca65..471d4b811 100644
--- a/client/messages/ja.json
+++ b/client/messages/ja.json
@@ -195,8 +195,8 @@
"Zx7WPP": "すべてのイベント系列が非表示です",
"AKRVhS": "凡例の項目をクリックして表示します",
"NuhCPH": "イベントのトラッキング方法を学ぶ",
- "/aq5/F": "カスタムイベントが見つかりません",
"ES6IYH": "別の日付範囲またはフィルターをお試しください",
+ "/aq5/F": "カスタムイベントが見つかりません",
"j7BiRg": "イベントが選択されていません。",
"kF9XUo": "タイムスタンプ",
"EwRIOm": "ユーザー",
@@ -597,8 +597,8 @@
"zINlao": "オーナー",
"iHN12u": "管理者",
"7L86Z5": "メンバー",
- "Nvr5Ce": "追加中...",
"v+BwPW": "組織に追加",
+ "Nvr5Ce": "追加中...",
"Msn3jj": "メールでフィルター...",
"gO9HzB": "ロールでフィルター",
"9nrF+x": "すべてのロール",
@@ -613,8 +613,6 @@
"J2wna+": "ユーザーを組織から削除しますか?",
"rDEYPT": "{email}を削除する組織を選択してください。その組織のすべてのリソースへのアクセスが失われます。",
"3Vr8ps": "管理者ダッシュボード",
- "OpgSlo": "管理者設定",
- "LaqXuS": "設定パネルは近日公開予定...",
"KI5ndC": "無効なドメイン形式です。example.comまたはsub.example.comのような有効なドメインを入力してください",
"cGNlRB": "Proにアップグレードしてウェブサイトを追加",
"UpxSPM": "ウェブサイトを追加するにはアクティブなサブスクリプションが必要です",
diff --git a/client/messages/ko.json b/client/messages/ko.json
index 7d581cded..b7c2bb2b6 100644
--- a/client/messages/ko.json
+++ b/client/messages/ko.json
@@ -195,8 +195,8 @@
"Zx7WPP": "모든 이벤트 시리즈 숨김",
"AKRVhS": "범례 항목을 클릭하여 표시",
"NuhCPH": "이벤트 추적 방법 알아보기",
- "/aq5/F": "사용자 정의 이벤트를 찾을 수 없음",
"ES6IYH": "다른 날짜 범위 또는 필터를 시도하세요",
+ "/aq5/F": "사용자 정의 이벤트를 찾을 수 없음",
"j7BiRg": "이벤트가 선택되지 않았습니다.",
"kF9XUo": "타임스탬프",
"EwRIOm": "사용자",
@@ -597,8 +597,8 @@
"zINlao": "소유자",
"iHN12u": "관리자",
"7L86Z5": "멤버",
- "Nvr5Ce": "추가 중...",
"v+BwPW": "조직에 추가",
+ "Nvr5Ce": "추가 중...",
"Msn3jj": "이메일로 필터...",
"gO9HzB": "역할로 필터",
"9nrF+x": "모든 역할",
@@ -613,8 +613,6 @@
"J2wna+": "사용자를 조직에서 제거하시겠습니까?",
"rDEYPT": "{email}을(를) 제거할 조직을 선택하세요. 해당 조직의 모든 리소스에 대한 액세스를 잃게 됩니다.",
"3Vr8ps": "관리자 대시보드",
- "OpgSlo": "관리자 설정",
- "LaqXuS": "설정 패널 곧 출시 예정...",
"KI5ndC": "잘못된 도메인 형식입니다. example.com 또는 sub.example.com과 같은 유효한 도메인이어야 합니다",
"cGNlRB": "Pro로 업그레이드하여 더 많은 웹사이트를 추가하세요",
"UpxSPM": "웹사이트를 추가하려면 활성 구독이 필요합니다",
diff --git a/client/messages/pl.json b/client/messages/pl.json
index cf4cbe5ef..e1cbe06d1 100644
--- a/client/messages/pl.json
+++ b/client/messages/pl.json
@@ -195,8 +195,8 @@
"Zx7WPP": "Wszystkie serie zdarzeń ukryte",
"AKRVhS": "Kliknij element legendy, aby go wyświetlić",
"NuhCPH": "Dowiedz się, jak śledzić zdarzenia",
- "/aq5/F": "Nie znaleziono niestandardowych zdarzeń",
"ES6IYH": "Spróbuj innego zakresu dat lub filtra",
+ "/aq5/F": "Nie znaleziono niestandardowych zdarzeń",
"j7BiRg": "Nie wybrano zdarzenia.",
"kF9XUo": "Znacznik czasu",
"EwRIOm": "Użytkownik",
@@ -597,8 +597,8 @@
"zINlao": "Właściciel",
"iHN12u": "Administrator",
"7L86Z5": "Członek",
- "Nvr5Ce": "Dodawanie...",
"v+BwPW": "Dodaj do organizacji",
+ "Nvr5Ce": "Dodawanie...",
"Msn3jj": "Filtruj po e-mailu...",
"gO9HzB": "Filtruj po roli",
"9nrF+x": "Wszystkie role",
@@ -613,8 +613,6 @@
"J2wna+": "Usunąć użytkownika z organizacji?",
"rDEYPT": "Wybierz organizację, z której chcesz usunąć {email}. Straci dostęp do wszystkich zasobów tej organizacji.",
"3Vr8ps": "Panel administratora",
- "OpgSlo": "Ustawienia administratora",
- "LaqXuS": "Panel ustawień wkrótce...",
"KI5ndC": "Nieprawidłowy format domeny. Musi być prawidłową domeną, np. example.com lub sub.example.com",
"cGNlRB": "Ulepsz do Pro, aby dodać więcej stron",
"UpxSPM": "Musisz mieć aktywną subskrypcję, aby dodawać strony",
diff --git a/client/messages/pt.json b/client/messages/pt.json
index 6b2512086..0202928b6 100644
--- a/client/messages/pt.json
+++ b/client/messages/pt.json
@@ -195,8 +195,8 @@
"Zx7WPP": "Todas as séries de eventos ocultas",
"AKRVhS": "Clique em um item da legenda para exibi-lo",
"NuhCPH": "Saiba como rastrear eventos",
- "/aq5/F": "Nenhum evento personalizado encontrado",
"ES6IYH": "Tente um intervalo de datas diferente ou filtro",
+ "/aq5/F": "Nenhum evento personalizado encontrado",
"j7BiRg": "Nenhum evento selecionado.",
"kF9XUo": "Data/Hora",
"EwRIOm": "Usuário",
@@ -597,8 +597,8 @@
"zINlao": "Proprietário",
"iHN12u": "Administrador",
"7L86Z5": "Membro",
- "Nvr5Ce": "Adicionando...",
"v+BwPW": "Adicionar à Organização",
+ "Nvr5Ce": "Adicionando...",
"Msn3jj": "Filtrar por email...",
"gO9HzB": "Filtrar por papel",
"9nrF+x": "Todos os Papéis",
@@ -613,8 +613,6 @@
"J2wna+": "Remover usuário da organização?",
"rDEYPT": "Selecione a organização da qual remover {email}. Ele perderá acesso a todos os recursos dessa organização.",
"3Vr8ps": "Painel Administrativo",
- "OpgSlo": "Configurações de Admin",
- "LaqXuS": "Painel de configurações em breve...",
"KI5ndC": "Formato de domínio inválido. Deve ser um domínio válido como exemplo.com ou sub.exemplo.com",
"cGNlRB": "Atualize para Pro para adicionar mais sites",
"UpxSPM": "Você precisa ter uma assinatura ativa para adicionar sites",
diff --git a/client/messages/zh.json b/client/messages/zh.json
index 120fe9feb..6064e1e4f 100644
--- a/client/messages/zh.json
+++ b/client/messages/zh.json
@@ -195,8 +195,8 @@
"Zx7WPP": "所有事件系列已隐藏",
"AKRVhS": "点击图例项以显示它",
"NuhCPH": "了解如何追踪事件",
- "/aq5/F": "未找到自定义事件",
"ES6IYH": "尝试不同的日期范围或过滤器",
+ "/aq5/F": "未找到自定义事件",
"j7BiRg": "未选择事件。",
"kF9XUo": "时间戳",
"EwRIOm": "用户",
@@ -597,8 +597,8 @@
"zINlao": "所有者",
"iHN12u": "管理员",
"7L86Z5": "成员",
- "Nvr5Ce": "正在添加...",
"v+BwPW": "添加到组织",
+ "Nvr5Ce": "正在添加...",
"Msn3jj": "按电子邮件过滤...",
"gO9HzB": "按角色过滤",
"9nrF+x": "所有角色",
@@ -613,8 +613,6 @@
"J2wna+": "从组织中移除用户?",
"rDEYPT": "选择要从中移除 {email} 的组织。他们将失去对该组织中所有资源的访问权限。",
"3Vr8ps": "管理仪表板",
- "OpgSlo": "管理设置",
- "LaqXuS": "设置面板即将推出...",
"KI5ndC": "无效的域名格式。必须是有效的域名,例如 example.com 或 sub.example.com",
"cGNlRB": "升级至 Pro 以添加更多网站",
"UpxSPM": "您需要有一个有效的订阅才能添加网站",
diff --git a/client/src/api/admin/endpoints/clickhouseStats.ts b/client/src/api/admin/endpoints/clickhouseStats.ts
new file mode 100644
index 000000000..b0a434cc7
--- /dev/null
+++ b/client/src/api/admin/endpoints/clickhouseStats.ts
@@ -0,0 +1,61 @@
+import { authedFetch } from "../../utils";
+
+export interface TableStats {
+ table: string;
+ totalRows: number;
+ compressedSize: string;
+ compressedBytes: number;
+ uncompressedSize: string;
+ uncompressedBytes: number;
+ partsCount: number;
+}
+
+export interface RowsByDate {
+ date: string;
+ table: string;
+ rowsInserted: number;
+}
+
+export interface InsertRate {
+ hour: string;
+ insertCount: number;
+ totalRowsInserted: number;
+}
+
+export interface QueryError {
+ eventTime: string;
+ queryId: string;
+ exceptionCode: number;
+ exception: string;
+ query: string;
+}
+
+export interface ClickhouseStatsResponse {
+ tableStats: TableStats[];
+ rowsByDate: RowsByDate[];
+ insertRate: InsertRate[];
+ queryErrors: QueryError[];
+ unavailableFeatures: string[];
+}
+
+export interface ActiveQuery {
+ queryId: string;
+ user: string;
+ query: string;
+ elapsed: number;
+ readRows: number;
+ memoryUsage: number;
+ queryKind: string;
+}
+
+export interface ClickhouseActiveQueriesResponse {
+ activeQueries: ActiveQuery[];
+}
+
+export function getClickhouseStats() {
+ return authedFetch<ClickhouseStatsResponse>("/admin/clickhouse-stats");
+}
+
+export function getClickhouseActiveQueries() {
+ return authedFetch<ClickhouseActiveQueriesResponse>("/admin/clickhouse-active-queries");
+}
diff --git a/client/src/api/admin/endpoints/index.ts b/client/src/api/admin/endpoints/index.ts
index 1fed5dd5b..70a32f640 100644
--- a/client/src/api/admin/endpoints/index.ts
+++ b/client/src/api/admin/endpoints/index.ts
@@ -80,3 +80,15 @@ export type { GetSiteImportsResponse, CreateSiteImportResponse } from "./import"
// Auth endpoints
export { getOrganizationMembers } from "./auth";
export type { GetOrganizationMembersResponse } from "./auth";
+
+// ClickHouse Stats endpoints
+export { getClickhouseStats, getClickhouseActiveQueries } from "./clickhouseStats";
+export type {
+ TableStats,
+ RowsByDate,
+ InsertRate,
+ QueryError,
+ ClickhouseStatsResponse,
+ ActiveQuery,
+ ClickhouseActiveQueriesResponse,
+} from "./clickhouseStats";
diff --git a/client/src/api/admin/hooks/useClickhouseStats.ts b/client/src/api/admin/hooks/useClickhouseStats.ts
new file mode 100644
index 000000000..b87a6912c
--- /dev/null
+++ b/client/src/api/admin/hooks/useClickhouseStats.ts
@@ -0,0 +1,23 @@
+import { useQuery } from "@tanstack/react-query";
+import {
+ getClickhouseStats,
+ getClickhouseActiveQueries,
+ ClickhouseStatsResponse,
+ ClickhouseActiveQueriesResponse,
+} from "../endpoints/clickhouseStats";
+
+export function useClickhouseStats() {
+ return useQuery<ClickhouseStatsResponse>({
+ queryKey: ["clickhouse-stats"],
+ queryFn: getClickhouseStats,
+ refetchInterval: 60000, // 60 seconds
+ });
+}
+
+export function useClickhouseActiveQueries() {
+ return useQuery<ClickhouseActiveQueriesResponse>({
+ queryKey: ["clickhouse-active-queries"],
+ queryFn: getClickhouseActiveQueries,
+ refetchInterval: 10000, // 10 seconds
+ });
+}
diff --git a/client/src/app/admin/components/database/ActiveQueriesTable.tsx b/client/src/app/admin/components/database/ActiveQueriesTable.tsx
new file mode 100644
index 000000000..2706f9889
--- /dev/null
+++ b/client/src/app/admin/components/database/ActiveQueriesTable.tsx
@@ -0,0 +1,106 @@
+"use client";
+
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { Skeleton } from "@/components/ui/skeleton";
+import { ActiveQuery } from "@/api/admin/endpoints/clickhouseStats";
+import { Badge } from "@/components/ui/badge";
+
+interface ActiveQueriesTableProps {
+ activeQueries: ActiveQuery[] | undefined;
+ isLoading: boolean;
+}
+
+function formatDuration(seconds: number): string {
+ if (seconds < 1) {
+ return `${(seconds * 1000).toFixed(0)}ms`;
+ }
+ if (seconds < 60) {
+ return `${seconds.toFixed(1)}s`;
+ }
+ const minutes = Math.floor(seconds / 60);
+ const remainingSeconds = seconds % 60;
+ return `${minutes}m ${remainingSeconds.toFixed(0)}s`;
+}
+
+function formatBytes(bytes: number): string {
+ if (bytes >= 1024 * 1024 * 1024) {
+ return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
+ }
+ if (bytes >= 1024 * 1024) {
+ return (bytes / (1024 * 1024)).toFixed(2) + " MB";
+ }
+ if (bytes >= 1024) {
+ return (bytes / 1024).toFixed(2) + " KB";
+ }
+ return bytes + " B";
+}
+
+function formatNumber(num: number): string {
+ if (num >= 1_000_000_000) {
+ return (num / 1_000_000_000).toFixed(1) + "B";
+ }
+ if (num >= 1_000_000) {
+ return (num / 1_000_000).toFixed(1) + "M";
+ }
+ if (num >= 1_000) {
+ return (num / 1_000).toFixed(1) + "K";
+ }
+ return num.toLocaleString();
+}
+
+export function ActiveQueriesTable({ activeQueries, isLoading }: ActiveQueriesTableProps) {
+ if (isLoading) {
+ return (
+ <div className="space-y-2">
+ {[...Array(3)].map((_, i) => (
+ <Skeleton key={i} className="h-12 w-full" />
+ ))}
+ </div>
+ );
+ }
+
+ if (!activeQueries || activeQueries.length === 0) {
+ return (
+ <div className="text-center py-8 text-neutral-500 dark:text-neutral-400">No active queries running</div>
+ );
+ }
+
+ return (
+ <div className="border rounded-lg overflow-hidden dark:border-neutral-800">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[100px]">User</TableHead>
+ <TableHead className="w-[100px]">Type</TableHead>
+ <TableHead className="w-[100px]">Elapsed</TableHead>
+ <TableHead className="w-[100px]">Rows Read</TableHead>
+ <TableHead className="w-[100px]">Memory</TableHead>
+ <TableHead>Query</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {activeQueries.map(query => (
+ <TableRow key={query.queryId}>
+ <TableCell className="font-medium">{query.user}</TableCell>
+ <TableCell>
+ <Badge variant="secondary" className="text-xs">
+ {query.queryKind || "Unknown"}
+ </Badge>
+ </TableCell>
+ <TableCell className={query.elapsed > 10 ? "text-amber-500" : ""}>
+ {formatDuration(query.elapsed)}
+ </TableCell>
+ <TableCell>{formatNumber(query.readRows)}</TableCell>
+ <TableCell>{formatBytes(query.memoryUsage)}</TableCell>
+ <TableCell>
+ <div className="max-w-md truncate font-mono text-xs text-neutral-600 dark:text-neutral-400">
+ {query.query}
+ </div>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/database/Database.tsx b/client/src/app/admin/components/database/Database.tsx
new file mode 100644
index 000000000..015382374
--- /dev/null
+++ b/client/src/app/admin/components/database/Database.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { useClickhouseStats, useClickhouseActiveQueries } from "@/api/admin/hooks/useClickhouseStats";
+import { TableStatsCards } from "./TableStatsCards";
+import { RowsTrendChart } from "./RowsTrendChart";
+import { InsertRateChart } from "./InsertRateChart";
+import { ActiveQueriesTable } from "./ActiveQueriesTable";
+import { QueryErrorsTable } from "./QueryErrorsTable";
+import { RefreshControls } from "./RefreshControls";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { Skeleton } from "@/components/ui/skeleton";
+
+function formatNumber(num: number): string {
+ if (num >= 1_000_000_000) {
+ return (num / 1_000_000_000).toFixed(2) + "B";
+ }
+ if (num >= 1_000_000) {
+ return (num / 1_000_000).toFixed(2) + "M";
+ }
+ if (num >= 1_000) {
+ return (num / 1_000).toFixed(2) + "K";
+ }
+ return num.toLocaleString();
+}
+
+function TableStatsTable({ tableStats, isLoading }: { tableStats: any[] | undefined; isLoading: boolean }) {
+ if (isLoading) {
+ return (
+ <div className="space-y-2">
+ {[...Array(4)].map((_, i) => (
+ <Skeleton key={i} className="h-10 w-full" />
+ ))}
+ </div>
+ );
+ }
+
+ if (!tableStats || tableStats.length === 0) {
+ return (
+ <div className="text-center py-8 text-neutral-500 dark:text-neutral-400">
+ No table statistics available
+ </div>
+ );
+ }
+
+ return (
+ <div className="border rounded-lg overflow-hidden dark:border-neutral-800">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Table</TableHead>
+ <TableHead className="text-right">Rows</TableHead>
+ <TableHead className="text-right">Compressed</TableHead>
+ <TableHead className="text-right">Uncompressed</TableHead>
+ <TableHead className="text-right">Ratio</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {tableStats.map(table => {
+ const compressionRatio =
+ table.uncompressedBytes > 0
+ ? ((1 - table.compressedBytes / table.uncompressedBytes) * 100).toFixed(1)
+ : "0";
+ return (
+ <TableRow key={table.table}>
+ <TableCell className="font-medium font-mono text-xs">{table.table}</TableCell>
+ <TableCell className="text-right text-xs">{formatNumber(table.totalRows)}</TableCell>
+ <TableCell className="text-right text-xs">{table.compressedSize}</TableCell>
+ <TableCell className="text-right text-xs">{table.uncompressedSize}</TableCell>
+ <TableCell className="text-right text-xs text-emerald-600 dark:text-emerald-400">
+ {compressionRatio}%
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
+
+export function Database() {
+ const queryClient = useQueryClient();
+ const [activeTab, setActiveTab] = useState("overview");
+ const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
+
+ const { data: stats, isLoading: statsLoading, isRefetching: statsRefetching, dataUpdatedAt } = useClickhouseStats();
+
+ const {
+ data: activeQueriesData,
+ isLoading: queriesLoading,
+ isRefetching: queriesRefetching,
+ } = useClickhouseActiveQueries();
+
+ // Update last updated time when data changes
+ if (dataUpdatedAt && (!lastUpdated || dataUpdatedAt > lastUpdated.getTime())) {
+ setLastUpdated(new Date(dataUpdatedAt));
+ }
+
+ const handleRefresh = () => {
+ queryClient.invalidateQueries({ queryKey: ["clickhouse-stats"] });
+ queryClient.invalidateQueries({ queryKey: ["clickhouse-active-queries"] });
+ };
+
+ const isRefetching = statsRefetching || queriesRefetching;
+
+ const isInsertRateUnavailable = stats?.unavailableFeatures?.includes("insertRate") ?? false;
+ const isQueryErrorsUnavailable = stats?.unavailableFeatures?.includes("queryErrors") ?? false;
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <div>
+ <h2 className="text-lg font-semibold">ClickHouse Database Health</h2>
+ <p className="text-sm text-neutral-500 dark:text-neutral-400">
+ Monitor database performance and storage metrics
+ </p>
+ </div>
+ <RefreshControls lastUpdated={lastUpdated} onRefresh={handleRefresh} isRefetching={isRefetching} />
+ </div>
+
+ <TableStatsCards tableStats={stats?.tableStats} isLoading={statsLoading} />
+
+ <Tabs defaultValue="overview" value={activeTab} onValueChange={setActiveTab}>
+ <TabsList>
+ <TabsTrigger value="overview">Overview</TabsTrigger>
+ <TabsTrigger value="queries">Active Queries</TabsTrigger>
+ <TabsTrigger value="errors">Query Errors</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="overview" className="space-y-4 mt-4">
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">Table Statistics</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <TableStatsTable tableStats={stats?.tableStats} isLoading={statsLoading} />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">Insert Rate (Last 24h)</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <InsertRateChart insertRate={stats?.insertRate} isLoading={statsLoading} isUnavailable={isInsertRateUnavailable} />
+ </CardContent>
+ </Card>
+ </div>
+
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">Rows Inserted by Table (Last 30 days)</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <RowsTrendChart rowsByDate={stats?.rowsByDate} isLoading={statsLoading} />
+ </CardContent>
+ </Card>
+ </TabsContent>
+
+ <TabsContent value="queries" className="mt-4">
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">
+ Active Queries
+ <span className="ml-2 text-sm font-normal text-neutral-500 dark:text-neutral-400">
+ (auto-refreshes every 10s)
+ </span>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <ActiveQueriesTable activeQueries={activeQueriesData?.activeQueries} isLoading={queriesLoading} />
+ </CardContent>
+ </Card>
+ </TabsContent>
+
+ <TabsContent value="errors" className="mt-4">
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">Query Errors (Last 24h)</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <QueryErrorsTable queryErrors={stats?.queryErrors} isLoading={statsLoading} isUnavailable={isQueryErrorsUnavailable} />
+ </CardContent>
+ </Card>
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/database/InsertRateChart.tsx b/client/src/app/admin/components/database/InsertRateChart.tsx
new file mode 100644
index 000000000..0d6d54990
--- /dev/null
+++ b/client/src/app/admin/components/database/InsertRateChart.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { ResponsiveLine } from "@nivo/line";
+import { useNivoTheme } from "@/lib/nivo";
+import { InsertRate } from "@/api/admin/endpoints/clickhouseStats";
+import { Skeleton } from "@/components/ui/skeleton";
+import { ChartTooltip } from "@/components/charts/ChartTooltip";
+import { DateTime } from "luxon";
+import { userLocale } from "@/lib/dateTimeUtils";
+import { useWindowSize } from "@uidotdev/usehooks";
+
+interface InsertRateChartProps {
+ insertRate: InsertRate[] | undefined;
+ isLoading: boolean;
+ isUnavailable?: boolean;
+}
+
+function formatNumber(num: number): string {
+ if (num >= 1_000_000_000) {
+ return (num / 1_000_000_000).toFixed(1) + "B";
+ }
+ if (num >= 1_000_000) {
+ return (num / 1_000_000).toFixed(1) + "M";
+ }
+ if (num >= 1_000) {
+ return (num / 1_000).toFixed(1) + "K";
+ }
+ return num.toString();
+}
+
+export function InsertRateChart({ insertRate, isLoading, isUnavailable }: InsertRateChartProps) {
+ const nivoTheme = useNivoTheme();
+ const { width } = useWindowSize();
+ const maxTicks = Math.round((width ?? Infinity) / 100);
+
+ if (isLoading) {
+ return (
+ <div className="h-64">
+ <Skeleton className="w-full h-full" />
+ </div>
+ );
+ }
+
+ if (isUnavailable) {
+ return (
+ <div className="h-64 flex flex-col items-center justify-center text-neutral-500 dark:text-neutral-400">
+ <p>Feature unavailable</p>
+ <p className="text-xs mt-1">system.query_log is disabled to save disk space</p>
+ </div>
+ );
+ }
+
+ if (!insertRate || insertRate.length === 0) {
+ return (
+ <div className="h-64 flex items-center justify-center text-neutral-500 dark:text-neutral-400">
+ No insert rate data available
+ </div>
+ );
+ }
+
+ const chartData = [
+ {
+ id: "Rows Inserted",
+ data: insertRate.map(row => ({
+ x: row.hour,
+ y: row.totalRowsInserted,
+ insertCount: row.insertCount,
+ currentTime: DateTime.fromSQL(row.hour, { zone: "utc" }),
+ })),
+ },
+ ];
+
+ const maxValue = Math.max(...insertRate.map(r => r.totalRowsInserted), 1);
+
+ return (
+ <div className="h-64">
+ <ResponsiveLine
+ data={chartData}
+ theme={nivoTheme}
+ margin={{ top: 10, right: 10, bottom: 25, left: 50 }}
+ xScale={{
+ type: "time",
+ format: "%Y-%m-%d %H:%M:%S",
+ precision: "hour",
+ useUTC: true,
+ }}
+ yScale={{
+ type: "linear",
+ min: 0,
+ max: maxValue,
+ stacked: false,
+ }}
+ enableGridX={false}
+ enableGridY={true}
+ gridYValues={5}
+ yFormat=" >-.0f"
+ axisTop={null}
+ axisRight={null}
+ axisBottom={{
+ tickSize: 0,
+ tickPadding: 10,
+ tickRotation: 0,
+ tickValues: Math.min(maxTicks, 12),
+ format: value => {
+ const dt = DateTime.fromJSDate(value).setLocale(userLocale);
+ return dt.toFormat("HH:mm");
+ },
+ }}
+ axisLeft={{
+ tickSize: 0,
+ tickPadding: 10,
+ tickRotation: 0,
+ tickValues: 5,
+ format: formatNumber,
+ }}
+ enablePoints={false}
+ useMesh={true}
+ animate={false}
+ enableSlices="x"
+ colors={["hsl(var(--emerald-400))"]}
+ enableArea={true}
+ areaOpacity={0.1}
+ sliceTooltip={({ slice }) => {
+ const point = slice.points[0];
+ const data = point?.data as any;
+ const currentTime = data?.currentTime as DateTime | undefined;
+
+ return (
+ <ChartTooltip>
+ <div className="p-3 min-w-[140px]">
+ <div className="font-medium mb-1">
+ {currentTime?.toLocaleString(DateTime.DATETIME_SHORT) ?? "Unknown"}
+ </div>
+ <div className="flex justify-between gap-4">
+ <span>Rows inserted:</span>
+ <span>{formatNumber(Number(point?.data.yFormatted ?? 0))}</span>
+ </div>
+ <div className="flex justify-between gap-4 text-neutral-500">
+ <span>Insert queries:</span>
+ <span>{data?.insertCount ?? 0}</span>
+ </div>
+ </div>
+ </ChartTooltip>
+ );
+ }}
+ />
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/database/QueryErrorsTable.tsx b/client/src/app/admin/components/database/QueryErrorsTable.tsx
new file mode 100644
index 000000000..236347bd8
--- /dev/null
+++ b/client/src/app/admin/components/database/QueryErrorsTable.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { Skeleton } from "@/components/ui/skeleton";
+import { QueryError } from "@/api/admin/endpoints/clickhouseStats";
+import { Badge } from "@/components/ui/badge";
+import { DateTime } from "luxon";
+
+interface QueryErrorsTableProps {
+ queryErrors: QueryError[] | undefined;
+ isLoading: boolean;
+ isUnavailable?: boolean;
+}
+
+export function QueryErrorsTable({ queryErrors, isLoading, isUnavailable }: QueryErrorsTableProps) {
+ if (isLoading) {
+ return (
+ <div className="space-y-2">
+ {[...Array(3)].map((_, i) => (
+ <Skeleton key={i} className="h-12 w-full" />
+ ))}
+ </div>
+ );
+ }
+
+ if (isUnavailable) {
+ return (
+ <div className="text-center py-8 text-neutral-500 dark:text-neutral-400">
+ <p>Feature unavailable</p>
+ <p className="text-xs mt-1">system.query_log is disabled to save disk space</p>
+ </div>
+ );
+ }
+
+ if (!queryErrors || queryErrors.length === 0) {
+ return (
+ <div className="text-center py-8 text-neutral-500 dark:text-neutral-400">
+ No query errors in the last 24 hours
+ </div>
+ );
+ }
+
+ return (
+ <div className="border rounded-lg overflow-hidden dark:border-neutral-800">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[160px]">Time</TableHead>
+ <TableHead className="w-[100px]">Error Code</TableHead>
+ <TableHead className="w-[300px]">Exception</TableHead>
+ <TableHead>Query</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {queryErrors.map(error => {
+ const eventTime = DateTime.fromSQL(error.eventTime, { zone: "utc" });
+ return (
+ <TableRow key={error.queryId}>
+ <TableCell className="text-xs">
+ {eventTime.toLocaleString(DateTime.DATETIME_SHORT)}
+ </TableCell>
+ <TableCell>
+ <Badge variant="destructive" className="text-xs">
+ {error.exceptionCode}
+ </Badge>
+ </TableCell>
+ <TableCell>
+ <div className="max-w-[300px] truncate text-xs text-red-600 dark:text-red-400">
+ {error.exception}
+ </div>
+ </TableCell>
+ <TableCell>
+ <div className="max-w-md truncate font-mono text-xs text-neutral-600 dark:text-neutral-400">
+ {error.query}
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/database/RefreshControls.tsx b/client/src/app/admin/components/database/RefreshControls.tsx
new file mode 100644
index 000000000..4908f8a5b
--- /dev/null
+++ b/client/src/app/admin/components/database/RefreshControls.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { RefreshCw } from "lucide-react";
+import { DateTime } from "luxon";
+
+interface RefreshControlsProps {
+ lastUpdated: Date | null;
+ onRefresh: () => void;
+ isRefetching: boolean;
+}
+
+export function RefreshControls({ lastUpdated, onRefresh, isRefetching }: RefreshControlsProps) {
+ const formattedTime = lastUpdated
+ ? DateTime.fromJSDate(lastUpdated).toLocaleString(DateTime.TIME_WITH_SECONDS)
+ : "Never";
+
+ return (
+ <div className="flex items-center gap-3">
+ <span className="text-sm text-neutral-500 dark:text-neutral-400">Last updated: {formattedTime}</span>
+ <Button variant="outline" size="sm" onClick={onRefresh} disabled={isRefetching}>
+ <RefreshCw className={`h-4 w-4 mr-2 ${isRefetching ? "animate-spin" : ""}`} />
+ Refresh
+ </Button>
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/database/RowsTrendChart.tsx b/client/src/app/admin/components/database/RowsTrendChart.tsx
new file mode 100644
index 000000000..dd4031570
--- /dev/null
+++ b/client/src/app/admin/components/database/RowsTrendChart.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { ResponsiveLine } from "@nivo/line";
+import { useNivoTheme } from "@/lib/nivo";
+import { RowsByDate } from "@/api/admin/endpoints/clickhouseStats";
+import { Skeleton } from "@/components/ui/skeleton";
+import { ChartTooltip } from "@/components/charts/ChartTooltip";
+import { DateTime } from "luxon";
+import { userLocale } from "@/lib/dateTimeUtils";
+import { useWindowSize } from "@uidotdev/usehooks";
+import { formatter } from "@/lib/utils";
+
+interface RowsTrendChartProps {
+ rowsByDate: RowsByDate[] | undefined;
+ isLoading: boolean;
+}
+
+export function RowsTrendChart({ rowsByDate, isLoading }: RowsTrendChartProps) {
+ const nivoTheme = useNivoTheme();
+ const { width } = useWindowSize();
+ const maxTicks = Math.round((width ?? Infinity) / 100);
+
+ if (isLoading) {
+ return (
+ <div className="h-64">
+ <Skeleton className="w-full h-full" />
+ </div>
+ );
+ }
+
+ if (!rowsByDate || rowsByDate.length === 0) {
+ return (
+ <div className="h-64 flex items-center justify-center text-neutral-500 dark:text-neutral-400">
+ No rows trend data available
+ </div>
+ );
+ }
+
+ // Group by table
+ const tableGroups = rowsByDate.reduce(
+ (acc, row) => {
+ if (!acc[row.table]) {
+ acc[row.table] = [];
+ }
+ acc[row.table].push(row);
+ return acc;
+ },
+ {} as Record<string, RowsByDate[]>
+ );
+
+ const colors = [
+ "hsl(var(--blue-400))",
+ "hsl(var(--indigo-400))",
+ "hsl(var(--violet-400))",
+ "hsl(var(--emerald-400))",
+ ];
+
+ // Filter to last 30 days to exclude bad/future dates
+ const now = DateTime.now();
+ const thirtyDaysAgo = now.minus({ days: 30 });
+
+ // Match GrowthChart pattern: use string dates directly
+ const chartData = Object.entries(tableGroups).map(([table, rows]) => ({
+ id: table,
+ data: rows
+ .map(row => {
+ const dt = DateTime.fromSQL(row.date);
+ return {
+ x: dt.toFormat("yyyy-MM-dd"),
+ y: row.rowsInserted,
+ currentTime: dt,
+ };
+ })
+ // Filter out invalid dates (future dates or dates outside the 30-day window)
+ .filter(point => point.currentTime.isValid && point.currentTime <= now && point.currentTime >= thirtyDaysAgo)
+ .sort((a, b) => a.currentTime.toMillis() - b.currentTime.toMillis()),
+ }));
+
+ return (
+ <div className="h-64">
+ <ResponsiveLine
+ data={chartData}
+ theme={nivoTheme}
+ margin={{ top: 10, right: 110, bottom: 25, left: 40 }}
+ xScale={{
+ type: "time",
+ format: "%Y-%m-%d",
+ precision: "day",
+ useUTC: true,
+ }}
+ yScale={{
+ type: "linear",
+ min: 0,
+ stacked: false,
+ reverse: false,
+ }}
+ enableGridX={true}
+ enableGridY={true}
+ gridYValues={5}
+ yFormat=" >-.0f"
+ axisTop={null}
+ axisRight={null}
+ axisBottom={{
+ tickSize: 0,
+ tickPadding: 10,
+ tickRotation: 0,
+ truncateTickAt: 0,
+ tickValues: Math.min(maxTicks, 10),
+ format: value => {
+ const dt = DateTime.fromJSDate(value).setLocale(userLocale);
+ return dt.toFormat("MMM d");
+ },
+ }}
+ axisLeft={{
+ tickSize: 0,
+ tickPadding: 10,
+ tickRotation: 0,
+ truncateTickAt: 0,
+ tickValues: 5,
+ format: formatter,
+ }}
+ enableTouchCrosshair={true}
+ enablePoints={false}
+ useMesh={true}
+ animate={false}
+ enableSlices="x"
+ colors={colors}
+ enableArea={false}
+ legends={[
+ {
+ anchor: "bottom-right",
+ direction: "column",
+ justify: false,
+ translateX: 100,
+ translateY: 0,
+ itemsSpacing: 0,
+ itemDirection: "left-to-right",
+ itemWidth: 80,
+ itemHeight: 20,
+ itemOpacity: 0.75,
+ symbolSize: 12,
+ symbolShape: "circle",
+ },
+ ]}
+ sliceTooltip={({ slice }: any) => {
+ const point = slice.points[0];
+
+ return (
+ <ChartTooltip>
+ <div className="p-3 min-w-[140px]">
+ <div className="font-medium mb-1">
+ {point.data.currentTime.toLocaleString(DateTime.DATE_SHORT)}
+ </div>
+ {slice.points.map((point: any) => (
+ <div key={point.seriesId} className="flex justify-between gap-4">
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: point.seriesColor }} />
+ <span className="text-xs truncate max-w-[80px]">{point.seriesId}</span>
+ </div>
+ <div>{formatter(Number(point.data.yFormatted))}</div>
+ </div>
+ ))}
+ </div>
+ </ChartTooltip>
+ );
+ }}
+ />
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/database/TableStatsCards.tsx b/client/src/app/admin/components/database/TableStatsCards.tsx
new file mode 100644
index 000000000..1203c33ba
--- /dev/null
+++ b/client/src/app/admin/components/database/TableStatsCards.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Skeleton } from "@/components/ui/skeleton";
+import { TableStats } from "@/api/admin/endpoints/clickhouseStats";
+import { Database, HardDrive, Layers, Server } from "lucide-react";
+
+interface TableStatsCardsProps {
+ tableStats: TableStats[] | undefined;
+ isLoading: boolean;
+}
+
+function formatNumber(num: number): string {
+ if (num >= 1_000_000_000) {
+ return (num / 1_000_000_000).toFixed(2) + "B";
+ }
+ if (num >= 1_000_000) {
+ return (num / 1_000_000).toFixed(2) + "M";
+ }
+ if (num >= 1_000) {
+ return (num / 1_000).toFixed(2) + "K";
+ }
+ return num.toLocaleString();
+}
+
+export function TableStatsCards({ tableStats, isLoading }: TableStatsCardsProps) {
+ if (isLoading) {
+ return (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
+ {[...Array(4)].map((_, i) => (
+ <Card key={i}>
+ <CardHeader className="pb-2">
+ <Skeleton className="h-4 w-24" />
+ </CardHeader>
+ <CardContent>
+ <Skeleton className="h-8 w-20" />
+ <Skeleton className="h-3 w-32 mt-2" />
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ );
+ }
+
+ if (!tableStats || tableStats.length === 0) {
+ return (
+ <div className="text-center py-8 text-neutral-500 dark:text-neutral-400">
+ No table statistics available
+ </div>
+ );
+ }
+
+ const totalRows = tableStats.reduce((sum, t) => sum + t.totalRows, 0);
+ const totalCompressedBytes = tableStats.reduce((sum, t) => sum + t.compressedBytes, 0);
+ const totalUncompressedBytes = tableStats.reduce((sum, t) => sum + t.uncompressedBytes, 0);
+ const totalParts = tableStats.reduce((sum, t) => sum + t.partsCount, 0);
+
+ const formatBytes = (bytes: number): string => {
+ if (bytes >= 1024 * 1024 * 1024) {
+ return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
+ }
+ if (bytes >= 1024 * 1024) {
+ return (bytes / (1024 * 1024)).toFixed(2) + " MB";
+ }
+ if (bytes >= 1024) {
+ return (bytes / 1024).toFixed(2) + " KB";
+ }
+ return bytes + " B";
+ };
+
+ const compressionRatio =
+ totalUncompressedBytes > 0 ? ((1 - totalCompressedBytes / totalUncompressedBytes) * 100).toFixed(1) : "0";
+
+ return (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
+ <CardTitle className="text-sm font-medium">Total Rows</CardTitle>
+ <Database className="h-4 w-4 text-neutral-500" />
+ </CardHeader>
+ <CardContent>
+ <div className="text-2xl font-bold">{formatNumber(totalRows)}</div>
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">Across {tableStats.length} tables</p>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
+ <CardTitle className="text-sm font-medium">Compressed Size</CardTitle>
+ <HardDrive className="h-4 w-4 text-neutral-500" />
+ </CardHeader>
+ <CardContent>
+ <div className="text-2xl font-bold">{formatBytes(totalCompressedBytes)}</div>
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">{compressionRatio}% compression ratio</p>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
+ <CardTitle className="text-sm font-medium">Uncompressed Size</CardTitle>
+ <Server className="h-4 w-4 text-neutral-500" />
+ </CardHeader>
+ <CardContent>
+ <div className="text-2xl font-bold">{formatBytes(totalUncompressedBytes)}</div>
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">Original data size</p>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
+ <CardTitle className="text-sm font-medium">Total Parts</CardTitle>
+ <Layers className="h-4 w-4 text-neutral-500" />
+ </CardHeader>
+ <CardContent>
+ <div className="text-2xl font-bold">{formatNumber(totalParts)}</div>
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">Active data parts</p>
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/client/src/app/admin/page.tsx b/client/src/app/admin/page.tsx
index 35b44c68a..9402ce37e 100644
--- a/client/src/app/admin/page.tsx
+++ b/client/src/app/admin/page.tsx
@@ -7,6 +7,7 @@ import { Sites } from "./components/sites/Sites";
import { Users } from "./components/users/Users";
import { Organizations } from "./components/organizations/Organizations";
import { AdminLayout } from "./components/shared/AdminLayout";
+import { Database } from "./components/database/Database";
import { AppSidebar } from "../../components/AppSidebar";
import { usePathname } from "next/navigation";
@@ -63,10 +64,10 @@ export default function AdminPage() {
<div className="text-2xl font-bold mb-4">{t("Admin Dashboard")}</div>
<Tabs defaultValue="organizations" value={activeTab} onValueChange={setActiveTab}>
<TabsList className="mb-4">
- <TabsTrigger value="organizations">{t("Organizations")}</TabsTrigger>
- <TabsTrigger value="sites">{t("Sites")}</TabsTrigger>
- <TabsTrigger value="users">{t("Users")}</TabsTrigger>
- <TabsTrigger value="settings">{t("Settings")}</TabsTrigger>
+ <TabsTrigger value="organizations">Organizations</TabsTrigger>
+ <TabsTrigger value="sites">Sites</TabsTrigger>
+ <TabsTrigger value="users">Users</TabsTrigger>
+ <TabsTrigger value="settings">Database</TabsTrigger>
</TabsList>
<TabsContent value="users">
@@ -82,10 +83,7 @@ export default function AdminPage() {
</TabsContent>
<TabsContent value="settings">
- <div className="p-4 border border-neutral-100 dark:border-neutral-800 rounded-md">
- <h2 className="text-xl font-bold mb-4">{t("Admin Settings")}</h2>
- <p className="text-muted-foreground">{t("Settings panel coming soon...")}</p>
- </div>
+ <Database />
</TabsContent>
</Tabs>
</AdminLayout>
diff --git a/server/src/api/admin/getClickhouseActiveQueries.ts b/server/src/api/admin/getClickhouseActiveQueries.ts
new file mode 100644
index 000000000..c537828a5
--- /dev/null
+++ b/server/src/api/admin/getClickhouseActiveQueries.ts
@@ -0,0 +1,51 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { clickhouse } from "../../db/clickhouse/clickhouse.js";
+
+interface ActiveQueryRow {
+ query_id: string;
+ user: string;
+ query: string;
+ elapsed: number;
+ read_rows: string;
+ memory_usage: string;
+ query_kind: string;
+}
+
+export async function getClickhouseActiveQueries(request: FastifyRequest, reply: FastifyReply) {
+ try {
+ const activeQueriesResult = await clickhouse.query({
+ query: `
+ SELECT
+ query_id,
+ user,
+ substring(query, 1, 500) as query,
+ elapsed,
+ read_rows,
+ memory_usage,
+ query_kind
+ FROM system.processes
+ WHERE is_cancelled = 0
+ AND query NOT LIKE '%system.processes%'
+ ORDER BY elapsed DESC
+ LIMIT 20
+ `,
+ format: "JSONEachRow",
+ });
+ const activeQueries = (await activeQueriesResult.json()) as ActiveQueryRow[];
+
+ return reply.status(200).send({
+ activeQueries: activeQueries.map(row => ({
+ queryId: row.query_id,
+ user: row.user,
+ query: row.query,
+ elapsed: row.elapsed,
+ readRows: Number(row.read_rows),
+ memoryUsage: Number(row.memory_usage),
+ queryKind: row.query_kind,
+ })),
+ });
+ } catch (error) {
+ request.log.error(error, "Failed to get ClickHouse active queries");
+ return reply.status(500).send({ error: "Failed to get ClickHouse active queries" });
+ }
+}
diff --git a/server/src/api/admin/getClickhouseStats.ts b/server/src/api/admin/getClickhouseStats.ts
new file mode 100644
index 000000000..05902af1a
--- /dev/null
+++ b/server/src/api/admin/getClickhouseStats.ts
@@ -0,0 +1,170 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { clickhouse } from "../../db/clickhouse/clickhouse.js";
+
+interface TableStatsRow {
+ table: string;
+ total_rows: string;
+ compressed_size: string;
+ compressed_bytes: string;
+ uncompressed_size: string;
+ uncompressed_bytes: string;
+ parts_count: string;
+}
+
+interface RowsByDateRow {
+ date: string;
+ table: string;
+ rows_inserted: string;
+}
+
+interface InsertRateRow {
+ hour: string;
+ insert_count: string;
+ total_rows_inserted: string;
+}
+
+interface QueryErrorRow {
+ event_time: string;
+ query_id: string;
+ exception_code: number;
+ exception: string;
+ query: string;
+}
+
+export async function getClickhouseStats(request: FastifyRequest, reply: FastifyReply) {
+ const unavailableFeatures: string[] = [];
+
+ try {
+ // Get table statistics (uses system.parts - always available)
+ const tableStatsResult = await clickhouse.query({
+ query: `
+ SELECT
+ table,
+ sum(rows) as total_rows,
+ formatReadableSize(sum(data_compressed_bytes)) as compressed_size,
+ sum(data_compressed_bytes) as compressed_bytes,
+ formatReadableSize(sum(data_uncompressed_bytes)) as uncompressed_size,
+ sum(data_uncompressed_bytes) as uncompressed_bytes,
+ count() as parts_count
+ FROM system.parts
+ WHERE database = currentDatabase() AND active = 1
+ AND table IN ('events', 'session_replay_events', 'session_replay_metadata', 'monitor_events')
+ GROUP BY table
+ ORDER BY total_rows DESC
+ `,
+ format: "JSONEachRow",
+ });
+ const tableStats = (await tableStatsResult.json()) as TableStatsRow[];
+
+ // Get rows by date (last 30 days) - query actual tables for accurate daily counts
+ const rowsByDateResult = await clickhouse.query({
+ query: `
+ SELECT date, table, rows_inserted FROM (
+ SELECT toDate(timestamp) as date, 'events' as table, count() as rows_inserted
+ FROM events
+ WHERE timestamp >= now() - INTERVAL 30 DAY
+ GROUP BY date
+ UNION ALL
+ SELECT toDate(timestamp) as date, 'session_replay_events' as table, count() as rows_inserted
+ FROM session_replay_events
+ WHERE timestamp >= now() - INTERVAL 30 DAY
+ GROUP BY date
+ UNION ALL
+ SELECT toDate(start_time) as date, 'session_replay_metadata' as table, count() as rows_inserted
+ FROM session_replay_metadata
+ WHERE start_time >= now() - INTERVAL 30 DAY
+ GROUP BY date
+ )
+ ORDER BY date, table
+ `,
+ format: "JSONEachRow",
+ });
+ const rowsByDate = (await rowsByDateResult.json()) as RowsByDateRow[];
+
+ // Get insert rate (last 24 hours) - uses system.query_log which may be disabled
+ let insertRate: InsertRateRow[] = [];
+ try {
+ const insertRateResult = await clickhouse.query({
+ query: `
+ SELECT
+ toStartOfHour(event_time) as hour,
+ count() as insert_count,
+ sum(written_rows) as total_rows_inserted
+ FROM system.query_log
+ WHERE type = 'QueryFinish'
+ AND query_kind = 'Insert'
+ AND event_time >= now() - INTERVAL 24 HOUR
+ GROUP BY hour
+ ORDER BY hour
+ `,
+ format: "JSONEachRow",
+ });
+ insertRate = (await insertRateResult.json()) as InsertRateRow[];
+ } catch (error: any) {
+ // system.query_log may be disabled to save disk space
+ request.log.debug("system.query_log not available - insert rate feature disabled");
+ unavailableFeatures.push("insertRate");
+ }
+
+ // Get query errors (last 24 hours) - uses system.query_log which may be disabled
+ let queryErrors: QueryErrorRow[] = [];
+ try {
+ const queryErrorsResult = await clickhouse.query({
+ query: `
+ SELECT
+ event_time,
+ query_id,
+ exception_code,
+ exception,
+ substring(query, 1, 500) as query
+ FROM system.query_log
+ WHERE type = 'ExceptionWhileProcessing'
+ AND event_time >= now() - INTERVAL 24 HOUR
+ ORDER BY event_time DESC
+ LIMIT 50
+ `,
+ format: "JSONEachRow",
+ });
+ queryErrors = (await queryErrorsResult.json()) as QueryErrorRow[];
+ } catch (error: any) {
+ // system.query_log may be disabled to save disk space
+ request.log.debug("system.query_log not available - query errors feature disabled");
+ if (!unavailableFeatures.includes("insertRate")) {
+ unavailableFeatures.push("queryErrors");
+ }
+ }
+
+ return reply.status(200).send({
+ tableStats: tableStats.map(row => ({
+ table: row.table,
+ totalRows: Number(row.total_rows),
+ compressedSize: row.compressed_size,
+ compressedBytes: Number(row.compressed_bytes),
+ uncompressedSize: row.uncompressed_size,
+ uncompressedBytes: Number(row.uncompressed_bytes),
+ partsCount: Number(row.parts_count),
+ })),
+ rowsByDate: rowsByDate.map(row => ({
+ date: row.date,
+ table: row.table,
+ rowsInserted: Number(row.rows_inserted),
+ })),
+ insertRate: insertRate.map(row => ({
+ hour: row.hour,
+ insertCount: Number(row.insert_count),
+ totalRowsInserted: Number(row.total_rows_inserted),
+ })),
+ queryErrors: queryErrors.map(row => ({
+ eventTime: row.event_time,
+ queryId: row.query_id,
+ exceptionCode: row.exception_code,
+ exception: row.exception,
+ query: row.query,
+ })),
+ unavailableFeatures,
+ });
+ } catch (error) {
+ request.log.error(error, "Failed to get ClickHouse stats");
+ return reply.status(500).send({ error: "Failed to get ClickHouse stats" });
+ }
+}
diff --git a/server/src/api/admin/index.ts b/server/src/api/admin/index.ts
index f01c9e444..b72b6cd1f 100644
--- a/server/src/api/admin/index.ts
+++ b/server/src/api/admin/index.ts
@@ -3,3 +3,5 @@ export { collectTelemetry } from "./collectTelemetry.js";
export { getAdminOrganizations } from "./getAdminOrganizations.js";
export { getAdminServiceEventCount } from "./getAdminServiceEventCount.js";
export { getAdminSites } from "./getAdminSites.js";
+export { getClickhouseStats } from "./getClickhouseStats.js";
+export { getClickhouseActiveQueries } from "./getClickhouseActiveQueries.js";
diff --git a/server/src/index.ts b/server/src/index.ts
index c654def31..c91ca63d6 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -10,6 +10,8 @@ import {
getAdminOrganizations,
getAdminServiceEventCount,
getAdminSites,
+ getClickhouseStats,
+ getClickhouseActiveQueries,
} from "./api/admin/index.js";
import {
createFunnel,
@@ -345,6 +347,10 @@ async function gscRoutes(fastify: FastifyInstance) {
}
async function stripeAdminRoutes(fastify: FastifyInstance) {
+ // ClickHouse stats (available for all admins)
+ fastify.get("/admin/clickhouse-stats", adminOnly, getClickhouseStats);
+ fastify.get("/admin/clickhouse-active-queries", adminOnly, getClickhouseActiveQueries);
+
// STRIPE & ADMIN
if (IS_CLOUD) {
// Stripe Routes