Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: db config, user profile details update, settings page added (#75)

Aman Agarwalb3162b2af2a3
diff --git a/src/client/README.md b/src/client/README.md
new file mode 100644
index 00000000..aa548dec
--- /dev/null
+++ b/src/client/README.md
@@ -0,0 +1,52 @@
+## Run Doku UI Client server
+![Next JS](https://img.shields.io/badge/Next-black?style=for-the-badge&logo=next.js&logoColor=white) ![TailwindCSS](https://img.shields.io/badge/tailwindcss-%2338B2AC.svg?style=for-the-badge&logo=tailwind-css&logoColor=white) ![Prisma](https://img.shields.io/badge/Prisma-3982CE?style=for-the-badge&logo=Prisma&logoColor=white) ![Clickhouse](https://img.shields.io/badge/clickhouse-faff69?style=for-the-badge&logo=clickhouse
+) ![Headless](https://img.shields.io/badge/headlessui-6dc0fd?style=for-the-badge&logo=headlessui
+) ![Next-Auth](https://img.shields.io/badge/next-auth-2cfefe?style=for-the-badge&logo=next-auth
+)
+
+Doku Client frontend uses Nextjs, Typescript and Tailwind. The application uses `@tremor/react` for charts, `react-hot-toast` for toasts, `@clickhouse/client` for clickhouse db client, `@prisma/client` for client's db for user management, db configuration management etc.
+
+# 📖 Table of Contents
+- [⚙️ Pre-requisites](#-pre-requisites)
+- [📌 The first step : Setup server without docker](#-the-first-step--setup-server-without-docker)
+- [🔌 Found a bug or want to request a feature](#found-a-bug-or-want-to-request-a-feature)
+- [Give A Star ⭐](#give-a-star-)
+
+### Pre-requisites:
+- `node` : version >=20
+- `postgres` : db for the doku client's storage (this comes under docker compose but if you setup without docker, then you need postgres db url to be set in env variable)
+
+### The first step : Setup server without docker
+1. Clone the doku repository
+ ```sh
+ git clone [email protected]:dokulabs/doku.git
+ ````
+2. Go to the client folder
+ ```sh
+ cd src/client
+ ````
+3. Install the dependencies
+ ```sh
+ npm install
+ ````
+4. Run command below to create an env file and then update the .env file for the `DATABASE_URL` to point to the postgres db
+ ```sh
+ cp .env.example .env
+ ````
+5. Apply the migrations to the postgres db using the below commands. First command applies the migrations to the db and the second command generates assets like Prisma Client based on the generator and data model blocks defined in your prisma/schema.prisma file.
+ ```sh
+ npx prisma migrate deploy
+ npx prisma generate
+ ````
+6. Start the dev server
+ ```sh
+ npm run dev
+ ````
+
+### Found a bug or want to request a feature
+
+Please open a [Github issue](https://github.com/dokulabs/doku/issues/new/choose).
+
+### Give A Star ⭐
+
+You can also give this repository a star to show more people and they can use this repository
\ No newline at end of file
diff --git a/src/client/colors.ts b/src/client/colors.ts
new file mode 100644
index 00000000..ef0a62b5
--- /dev/null
+++ b/src/client/colors.ts
@@ -0,0 +1,14 @@
+export const COLORS = {
+ primary: "#F36C06",
+ secondary: "#FFF4D8",
+ tertiary: "#212738",
+ white: "#F9F9F9",
+ error: "#ED474A",
+ darkMode: {
+ primary: "#0C120C",
+ secondary: "#212738",
+ tertiary: "#FFF4D8",
+ white: "#F9F9F9",
+ error: "#ED474A",
+ },
+};
diff --git a/src/client/package-lock.json b/src/client/package-lock.json
index f911e9df..c23d7cc7 100644
--- a/src/client/package-lock.json
+++ b/src/client/package-lock.json
@@ -8,6 +8,7 @@
"name": "doku",
"version": "0.1.0",
"dependencies": {
+ "@clickhouse/client": "^0.2.10",
"@headlessui/react": "^1.7.18",
"@heroicons/react": "^2.1.1",
"@next-auth/prisma-adapter": "^1.0.7",
@@ -16,11 +17,13 @@
"bcrypt-ts": "^5.0.1",
"copy-to-clipboard": "^3.3.3",
"date-fns": "^3.3.1",
+ "generic-pool": "^3.9.0",
"lodash": "^4.17.21",
"next": "14.0.4",
"next-auth": "^4.24.5",
"react": "^18",
"react-dom": "^18",
+ "react-hot-toast": "^2.4.1",
"react-syntax-highlighter": "^15.5.0"
},
"devDependencies": {
@@ -69,6 +72,22 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@clickhouse/client": {
+ "version": "0.2.10",
+ "resolved": "https://registry.npmjs.org/@clickhouse/client/-/client-0.2.10.tgz",
+ "integrity": "sha512-ZwBgzjEAFN/ogS0ym5KHVbR7Hx/oYCX01qGp2baEyfN2HM73kf/7Vp3GvMHWRy+zUXISONEtFv7UTViOXnmFrg==",
+ "dependencies": {
+ "@clickhouse/client-common": "0.2.10"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@clickhouse/client-common": {
+ "version": "0.2.10",
+ "resolved": "https://registry.npmjs.org/@clickhouse/client-common/-/client-common-0.2.10.tgz",
+ "integrity": "sha512-BvTY0IXS96y9RUeNCpKL4HUzHmY80L0lDcGN0lmUD6zjOqYMn78+xyHYJ/AIAX7JQsc+/KwFt2soZutQTKxoGQ=="
+ },
"node_modules/@eslint-community/eslint-utils": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz",
@@ -2606,6 +2625,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/generic-pool": {
+ "version": "3.9.0",
+ "resolved": "https://registry.npmjs.org/generic-pool/-/generic-pool-3.9.0.tgz",
+ "integrity": "sha512-hymDOu5B53XvN4QT9dBmZxPX4CWhBPPLguTZ9MMFeFa/Kg0xWVfylOVNlJji/E7yTZWFd/q9GO5TxDLq156D7g==",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
"node_modules/get-intrinsic": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz",
@@ -2735,6 +2762,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/goober": {
+ "version": "2.1.14",
+ "resolved": "https://registry.npmjs.org/goober/-/goober-2.1.14.tgz",
+ "integrity": "sha512-4UpC0NdGyAFqLNPnhCT2iHpza2q+RAY3GV85a/mRPdzyPQMsj0KmMMuetdIkzWRbJ+Hgau1EZztq8ImmiMGhsg==",
+ "peerDependencies": {
+ "csstype": "^3.0.10"
+ }
+ },
"node_modules/gopd": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz",
@@ -4378,6 +4413,21 @@
"react": "^18.2.0"
}
},
+ "node_modules/react-hot-toast": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.4.1.tgz",
+ "integrity": "sha512-j8z+cQbWIM5LY37pR6uZR6D4LfseplqnuAO4co4u8917hBUvXlEqyP1ZzqVLcqoyUesZZv/ImreoCeHVDpE5pQ==",
+ "dependencies": {
+ "goober": "^2.1.10"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "peerDependencies": {
+ "react": ">=16",
+ "react-dom": ">=16"
+ }
+ },
"node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
diff --git a/src/client/package.json b/src/client/package.json
index 87ff0b00..94284f47 100644
--- a/src/client/package.json
+++ b/src/client/package.json
@@ -9,6 +9,7 @@
"lint": "next lint"
},
"dependencies": {
+ "@clickhouse/client": "^0.2.10",
"@headlessui/react": "^1.7.18",
"@heroicons/react": "^2.1.1",
"@next-auth/prisma-adapter": "^1.0.7",
@@ -17,11 +18,13 @@
"bcrypt-ts": "^5.0.1",
"copy-to-clipboard": "^3.3.3",
"date-fns": "^3.3.1",
+ "generic-pool": "^3.9.0",
"lodash": "^4.17.21",
"next": "14.0.4",
"next-auth": "^4.24.5",
"react": "^18",
"react-dom": "^18",
+ "react-hot-toast": "^2.4.1",
"react-syntax-highlighter": "^15.5.0"
},
"devDependencies": {
diff --git a/src/client/prisma/migrations/0_init/migration.sql b/src/client/prisma/migrations/0_init/migration.sql
new file mode 100644
index 00000000..4895924b
--- /dev/null
+++ b/src/client/prisma/migrations/0_init/migration.sql
@@ -0,0 +1,79 @@
+-- CreateTable
+CREATE TABLE "accounts" (
+ "id" TEXT NOT NULL,
+ "user_id" TEXT NOT NULL,
+ "type" TEXT,
+ "provider" TEXT NOT NULL,
+ "provider_account_id" TEXT NOT NULL,
+ "token_type" TEXT,
+ "refresh_token" TEXT,
+ "access_token" TEXT,
+ "expires_at" INTEGER,
+ "scope" TEXT,
+ "id_token" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "accounts_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "sessions" (
+ "id" TEXT NOT NULL,
+ "user_id" TEXT,
+ "session_token" TEXT NOT NULL,
+ "access_token" TEXT,
+ "expires" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "users" (
+ "id" TEXT NOT NULL,
+ "name" TEXT,
+ "email" TEXT NOT NULL,
+ "email_verified" TIMESTAMP(3),
+ "password" TEXT,
+ "image" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "VerificationRequest" (
+ "id" TEXT NOT NULL,
+ "identifier" TEXT NOT NULL,
+ "token" TEXT NOT NULL,
+ "expires" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "VerificationRequest_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "accounts_provider_provider_account_id_key" ON "accounts"("provider", "provider_account_id");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "sessions_session_token_key" ON "sessions"("session_token");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "VerificationRequest_token_key" ON "VerificationRequest"("token");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "VerificationRequest_identifier_token_key" ON "VerificationRequest"("identifier", "token");
+
+-- AddForeignKey
+ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/src/client/prisma/migrations/20240227112228_database_config/migration.sql b/src/client/prisma/migrations/20240227112228_database_config/migration.sql
new file mode 100644
index 00000000..5e6b48b1
--- /dev/null
+++ b/src/client/prisma/migrations/20240227112228_database_config/migration.sql
@@ -0,0 +1,61 @@
+/*
+ Warnings:
+
+ - You are about to drop the `VerificationRequest` table. If the table is not empty, all the data it contains will be lost.
+
+*/
+-- DropTable
+DROP TABLE "VerificationRequest";
+
+-- CreateTable
+CREATE TABLE "verificationrequest" (
+ "id" TEXT NOT NULL,
+ "identifier" TEXT NOT NULL,
+ "token" TEXT NOT NULL,
+ "expires" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "verificationrequest_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "databaseconfig" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "environment" TEXT NOT NULL DEFAULT 'production',
+ "meta" JSONB NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ "user_id" TEXT NOT NULL,
+
+ CONSTRAINT "databaseconfig_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "databaseconfiguser" (
+ "databaseConfigId" TEXT NOT NULL,
+ "user_id" TEXT NOT NULL,
+ "isCurrent" BOOLEAN NOT NULL DEFAULT false
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "verificationrequest_token_key" ON "verificationrequest"("token");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "verificationrequest_identifier_token_key" ON "verificationrequest"("identifier", "token");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "databaseconfig_name_key" ON "databaseconfig"("name");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "databaseconfiguser_databaseConfigId_user_id_key" ON "databaseconfiguser"("databaseConfigId", "user_id");
+
+-- AddForeignKey
+ALTER TABLE "databaseconfig" ADD CONSTRAINT "databaseconfig_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "databaseconfiguser" ADD CONSTRAINT "databaseconfiguser_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "databaseconfiguser" ADD CONSTRAINT "databaseconfiguser_databaseConfigId_fkey" FOREIGN KEY ("databaseConfigId") REFERENCES "databaseconfig"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/src/client/prisma/migrations/migration_lock.toml b/src/client/prisma/migrations/migration_lock.toml
new file mode 100644
index 00000000..fbffa92c
--- /dev/null
+++ b/src/client/prisma/migrations/migration_lock.toml
@@ -0,0 +1,3 @@
+# Please do not edit this file manually
+# It should be added in your version-control system (i.e. Git)
+provider = "postgresql"
\ No newline at end of file
diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prisma
index 5b8ed400..93722325 100644
--- a/src/client/prisma/schema.prisma
+++ b/src/client/prisma/schema.prisma
@@ -1,5 +1,5 @@
generator client {
- provider = "prisma-client-js"
+ provider = "prisma-client-js"
binaryTargets = ["native", "linux-arm64-openssl-3.0.x"]
}
@@ -8,73 +8,33 @@ datasource db {
url = env("DATABASE_URL")
}
-model doku_apikeys {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
- api_key String @unique @db.VarChar(255)
- name String @db.VarChar(50)
- created_at DateTime? @default(now()) @db.Timestamptz(6)
-
- @@index([api_key], map: "idx_api_key")
-}
-
-/// This table has subclasses and requires additional setup for migrations. Visit https://pris.ly/d/table-inheritance for more info.
-/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
-model doku_llm_data {
- time DateTime @db.Timestamptz(6)
- id String? @default(dbgenerated("gen_random_uuid()")) @db.Uuid
- llmreqid String?
- environment String @db.VarChar(50)
- endpoint String @db.VarChar(50)
- sourcelanguage String @db.VarChar(50)
- applicationname String @db.VarChar(50)
- completiontokens Int?
- prompttokens Int?
- totaltokens Int?
- finishreason String? @db.VarChar(50)
- requestduration Float?
- usagecost Float?
- model String? @db.VarChar(50)
- prompt String?
- response String?
- imagesize String?
- revisedprompt String?
- image String?
- audiovoice String?
- finetunejobstatus String?
-
- @@index([time(sort: Desc)])
- @@ignore
-}
-
-
model Account {
- id String @id @default(cuid())
- userId String @map("user_id")
- type String?
- provider String
- providerAccountId String @map("provider_account_id")
- token_type String?
- refresh_token String? @db.Text
- access_token String? @db.Text
- expires_at Int?
- scope String?
- id_token String? @db.Text
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ id String @id @default(cuid())
+ userId String @map("user_id")
+ type String?
+ provider String
+ providerAccountId String @map("provider_account_id")
+ token_type String?
+ refresh_token String? @db.Text
+ access_token String? @db.Text
+ expires_at Int?
+ scope String?
+ id_token String? @db.Text
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
@@map("accounts")
}
-
model Session {
id String @id @default(cuid())
userId String? @map("user_id")
- sessionToken String @db.Text @map("session_token") @unique
- accessToken String? @db.Text @map("access_token")
+ sessionToken String @unique @map("session_token") @db.Text
+ accessToken String? @map("access_token") @db.Text
expires DateTime
- user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
+ user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -82,16 +42,19 @@ model Session {
}
model User {
- id String @id @default(uuid())
- name String?
- email String @unique
- emailVerified DateTime? @map("email_verified")
- password String?
- image String?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- accounts Account[]
- sessions Session[]
+ id String @id @default(uuid())
+ name String?
+ email String @unique
+ emailVerified DateTime? @map("email_verified")
+ password String?
+ image String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ accounts Account[]
+ sessions Session[]
+ dbConfigs DatabaseConfigUser[]
+ createdDBConfigs DatabaseConfig[]
+
@@map("users")
}
@@ -104,4 +67,32 @@ model VerificationRequest {
updatedAt DateTime @updatedAt
@@unique([identifier, token])
-}
\ No newline at end of file
+ @@map("verificationrequest")
+}
+
+// Database Config
+model DatabaseConfig {
+ id String @id @default(cuid())
+ name String
+ environment String @default("production")
+ meta Json
+ dbUsers DatabaseConfigUser[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ createdByUserId String @map("user_id")
+ createdByUser User @relation(fields: [createdByUserId], references: [id])
+
+ @@unique([name])
+ @@map("databaseconfig")
+}
+
+model DatabaseConfigUser {
+ databaseConfigId String
+ userId String @map("user_id")
+ user User @relation(fields: [userId], references: [id])
+ databaseConfig DatabaseConfig? @relation(fields: [databaseConfigId], references: [id])
+ isCurrent Boolean @default(false)
+
+ @@unique([databaseConfigId, userId])
+ @@map("databaseconfiguser")
+}
diff --git a/src/client/src/app/(playground)/dashboard/requests-per-time.tsx b/src/client/src/app/(playground)/dashboard/requests-per-time.tsx
index 099d0d83..2c0f3eb7 100644
--- a/src/client/src/app/(playground)/dashboard/requests-per-time.tsx
+++ b/src/client/src/app/(playground)/dashboard/requests-per-time.tsx
@@ -3,6 +3,7 @@ import { useFilter } from "../filter-context";
import Card from "@/components/common/card";
import { LineChart } from "@tremor/react";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import toast from "react-hot-toast";
export default function RequestsPerTime() {
const [filter] = useFilter();
@@ -15,6 +16,11 @@ export default function RequestsPerTime() {
requestType: "POST",
url: "/api/metrics/request/time",
responseDataKey: "data",
+ failureCb: (err?: string) => {
+ toast.error(err || `Cannot connect to server!`, {
+ id: "dashboard-page",
+ });
+ },
});
}, [filter]);
diff --git a/src/client/src/app/(playground)/requests/page.tsx b/src/client/src/app/(playground)/requests/page.tsx
index b9143a08..249aad16 100644
--- a/src/client/src/app/(playground)/requests/page.tsx
+++ b/src/client/src/app/(playground)/requests/page.tsx
@@ -6,6 +6,7 @@ import RequestFilter, { FilterConfigProps } from "./request-filter";
import { RequestProvider } from "./request-context";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import RequestDetails from "./request-details";
+import toast from "react-hot-toast";
export default function RequestPage() {
const [filter] = useFilter();
@@ -26,6 +27,11 @@ export default function RequestPage() {
}),
requestType: "POST",
url: "/api/metrics/request",
+ failureCb: (err?: string) => {
+ toast.error(err || `Cannot connect to server!`, {
+ id: "request-page",
+ });
+ },
});
}, [filter]);
diff --git a/src/client/src/app/(playground)/requests/request-context.tsx b/src/client/src/app/(playground)/requests/request-context.tsx
index 2c0622e3..42a4968b 100644
--- a/src/client/src/app/(playground)/requests/request-context.tsx
+++ b/src/client/src/app/(playground)/requests/request-context.tsx
@@ -2,15 +2,15 @@ import { noop } from "@/utils/noop";
import { ReactNode, createContext, useContext, useState } from "react";
export const RequestMappings = {
- applicationname: {
+ applicationName: {
label: "Application Name",
type: "string",
},
- audiovoice: {
+ audioVoice: {
label: "Audio Voice",
type: "string",
},
- completiontokens: {
+ completionTokens: {
label: "Completion Tokens",
type: "string",
},
@@ -22,15 +22,15 @@ export const RequestMappings = {
label: "Environment",
type: "string",
},
- finetunejobid: {
+ finetuneJobid: {
label: "Fine Tune Job Id",
type: "string",
},
- finetunejobstatus: {
+ finetuneJobStatus: {
label: "Fine Tune Job Status",
type: "string",
},
- finishreason: {
+ finishReason: {
label: "Finish Reason",
type: "string",
},
@@ -42,7 +42,7 @@ export const RequestMappings = {
label: "Image",
type: "string",
},
- imagesize: {
+ imageSize: {
label: "Image Size",
type: "string",
},
@@ -58,11 +58,11 @@ export const RequestMappings = {
label: "Prompt",
type: "string",
},
- prompttokens: {
+ promptTokens: {
label: "Prompt Tokens",
type: "string",
},
- requestduration: {
+ requestDuration: {
label: "Request Duration",
type: "string",
},
@@ -70,11 +70,11 @@ export const RequestMappings = {
label: "Response",
type: "string",
},
- revisedprompt: {
+ revisedPrompt: {
label: "Revised Prompt",
type: "string",
},
- sourcelanguage: {
+ sourceLanguage: {
label: "Source Language",
type: "string",
},
@@ -82,11 +82,11 @@ export const RequestMappings = {
label: "Time",
type: "string",
},
- totaltokens: {
+ totalTokens: {
label: "Total Tokens",
type: "string",
},
- usagecost: {
+ usageCost: {
label: "Usage Cost",
type: "string",
},
@@ -95,15 +95,15 @@ export const RequestMappings = {
export const DisplayDataRequestMappingKeys: Array<
keyof typeof RequestMappings
> = [
- "applicationname",
+ "applicationName",
"endpoint",
"model",
- "requestduration",
- "prompttokens",
- "totaltokens",
- "usagecost",
+ "requestDuration",
+ "promptTokens",
+ "totalTokens",
+ "usageCost",
"time",
- "sourcelanguage",
+ "sourceLanguage",
];
type RequestProps = Record<keyof typeof RequestMappings, any> | null;
diff --git a/src/client/src/app/(playground)/requests/request-details.tsx b/src/client/src/app/(playground)/requests/request-details.tsx
index bb4ffd7b..6e10d19b 100644
--- a/src/client/src/app/(playground)/requests/request-details.tsx
+++ b/src/client/src/app/(playground)/requests/request-details.tsx
@@ -60,7 +60,7 @@ export default function RequestDetails() {
<div className="p-4 bg-secondary relative">
<div className="flex flex-col">
<Dialog.Title className="text-2xl font-bold leading-7 text-tertiary">
- {request.applicationname}
+ {request.applicationName}
</Dialog.Title>
<div className="flex items-center mt-3 text-tertiary/[.7]">
<BeakerIcon className="w-4 mr-3" />
@@ -102,7 +102,7 @@ export default function RequestDetails() {
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<ClockIcon className="w-3" />
<span>Request duration : </span>
- <span>{round(request.requestduration, 4)}s</span>
+ <span>{round(request.requestDuration, 4)}s</span>
</div>
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<CogIcon className="w-3" />
@@ -112,44 +112,44 @@ export default function RequestDetails() {
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<CurrencyDollarIcon className="w-3" />
<span>Usage cost : </span>
- <span>{round(request.usagecost, 6)}</span>
+ <span>{round(request.usageCost, 6)}</span>
</div>
- {request.prompttokens && (
+ {request.promptTokens && (
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<ClipboardDocumentCheckIcon className="w-3" />
<span>Prompt tokens : </span>
- <span>{request.prompttokens}</span>
+ <span>{request.promptTokens}</span>
</div>
)}
- {request.totaltokens && (
+ {request.totalTokens && (
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<ClipboardDocumentListIcon className="w-3" />
<span>Total tokens : </span>
- <span>{request.totaltokens}</span>
+ <span>{request.totalTokens}</span>
</div>
)}
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<LanguageIcon className="w-3" />
<span>Source Language : </span>
- <span>{request.sourcelanguage}</span>
+ <span>{request.sourceLanguage}</span>
</div>
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<GlobeAltIcon className="w-3" />
<span>Environment : </span>
<span>{request.environment}</span>
</div>
- {request.audiovoice && (
+ {request.audioVoice && (
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<SpeakerWaveIcon className="w-3" />
<span>Audio voice : </span>
- <span>{request.audiovoice}</span>
+ <span>{request.audioVoice}</span>
</div>
)}
- {request.imagesize && (
+ {request.imageSize && (
<div className="flex items-center justify-center space-x-1 px-3 py-1 rounded-full text-xs bg-primary/[0.1] text-primary font-medium">
<PhotoIcon className="w-3" />
<span>Image size : </span>
- <span>{request.imagesize}</span>
+ <span>{request.imageSize}</span>
</div>
)}
</div>
@@ -161,13 +161,13 @@ export default function RequestDetails() {
{request.prompt}
</code>
</div>
- {request.revisedprompt && (
+ {request.revisedPrompt && (
<div className="flex flex-col space-y-3 mt-4">
<span className="text-sm text-tertiary/[0.8] font-medium">
Revised Prompt :{" "}
</span>
<code className="text-sm inline-flex text-left items-center bg-tertiary text-secondary rounded-md p-4">
- {request.prompt}
+ {request.revisedPrompt}
</code>
</div>
)}
@@ -181,18 +181,18 @@ export default function RequestDetails() {
</code>
</div>
)}
- {request.image && request.imagesize && (
+ {request.image && request.imageSize && (
<div className="flex items-center justify-center aspect-h-1 aspect-w-1 w-full overflow-hidden rounded-md bg-tertiary/[0.1] lg:aspect-none group-hover:opacity-75 lg:h-80 mt-4">
<Image
src={request.image}
- alt={request.applicationname}
+ alt={request.applicationName}
className="h-full w-full object-cover object-center lg:h-full lg:w-full"
width={parseInt(
- request.imagesize.split("x")[0],
+ request.imageSize.split("x")[0],
10
)}
height={parseInt(
- request.imagesize.split("x")[1],
+ request.imageSize.split("x")[1],
10
)}
/>
diff --git a/src/client/src/app/(playground)/requests/request-table.tsx b/src/client/src/app/(playground)/requests/request-table.tsx
index f6aacd57..c82ad547 100644
--- a/src/client/src/app/(playground)/requests/request-table.tsx
+++ b/src/client/src/app/(playground)/requests/request-table.tsx
@@ -66,7 +66,7 @@ const RenderRow = ({ item, isLoading }: RenderRowProps) => {
<div className="flex items-center pl-3 border-l border-tertiary/[0.2]">
<ClockIcon className="w-4" />
<p className="text-xs leading-none ml-2">
- {round(item.requestduration, 4)}s
+ {round(item.requestDuration, 4)}s
</p>
</div>
</div>
@@ -79,7 +79,7 @@ const RenderRow = ({ item, isLoading }: RenderRowProps) => {
<RowItem
containerClass="w-3/12"
label="App name"
- text={item.applicationname}
+ text={item.applicationName}
textClass="font-medium"
/>
<RowItem
@@ -100,21 +100,21 @@ const RenderRow = ({ item, isLoading }: RenderRowProps) => {
containerClass="w-1.5/12"
icon={<CurrencyDollarIcon className="w-4" />}
label="Usage cost"
- text={`${round(item.usagecost, 6)}`}
+ text={`${round(item.usageCost, 6)}`}
textClass="text-sm"
/>
<RowItem
containerClass="w-1.5/12"
icon={<ClipboardDocumentCheckIcon className="w-4" />}
label="Prompt Tokens"
- text={`${item.prompttokens || "-"}`}
+ text={`${item.promptTokens || "-"}`}
textClass="text-sm"
/>
<RowItem
containerClass="w-1.5/12"
icon={<ClipboardDocumentListIcon className="w-4" />}
label="Total Tokens"
- text={`${item.totaltokens || "-"}`}
+ text={`${item.totalTokens || "-"}`}
textClass="text-sm"
/>
</div>
diff --git a/src/client/src/app/(playground)/settings/database.tsx b/src/client/src/app/(playground)/settings/database.tsx
new file mode 100644
index 00000000..aec97bc9
--- /dev/null
+++ b/src/client/src/app/(playground)/settings/database.tsx
@@ -0,0 +1,305 @@
+import SideTabs, { SideTabItemProps } from "@/components/common/side-tabs";
+import { DB_META_KEYS } from "@/constants/dbConfig";
+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import { noop } from "@/utils/noop";
+import { CheckIcon, TrashIcon } from "@heroicons/react/24/outline";
+import { keyBy } from "lodash";
+import {
+ FormEventHandler,
+ MouseEventHandler,
+ useCallback,
+ useEffect,
+ useState,
+} from "react";
+import toast from "react-hot-toast";
+
+type DBConfig = {
+ id: string;
+ name: string;
+ environment: string;
+ meta: Record<string, any>;
+ isCurrent?: boolean;
+};
+
+function ModifyDatabaseConfig({
+ dbConfig,
+ successCb,
+}: {
+ dbConfig?: DBConfig;
+ successCb: () => void;
+}) {
+ const { fireRequest, isLoading } = useFetchWrapper();
+
+ const modifyDetails: FormEventHandler<HTMLFormElement> = useCallback(
+ (event) => {
+ event.preventDefault();
+ const formElement = event.target as HTMLFormElement;
+
+ toast.loading("Modifying db config...", {
+ id: "db-config-details",
+ });
+
+ fireRequest({
+ body: JSON.stringify({
+ id: dbConfig?.id,
+ name: (formElement.name as any)?.value,
+ environment: (formElement.environment as any)?.value,
+ meta: {
+ [DB_META_KEYS.url]: (formElement[DB_META_KEYS.url] as any)?.value,
+ },
+ }),
+ requestType: "POST",
+ url: "/api/db-config",
+ responseDataKey: "data",
+ successCb: () => {
+ successCb();
+ toast.success("Db config updated!", {
+ id: "db-config-details",
+ });
+ if (!dbConfig?.id) formElement.reset();
+ },
+ failureCb: (err?: string) => {
+ toast.error(err || "Db config updation failed!", {
+ id: "db-config-details",
+ });
+ },
+ });
+ },
+ [dbConfig?.id]
+ );
+
+ return (
+ <form
+ className="flex flex-col w-full"
+ onSubmit={isLoading ? noop : modifyDetails}
+ >
+ <div className="flex flex-col relative flex-1 overflow-y-auto px-5 py-3">
+ <h2 className="text-base font-semibold text-tertiary sticky top-0 bg-white">
+ {dbConfig?.id ? "Update" : "Add"} database config
+ </h2>
+
+ <div className="flex flex-col mt-6 w-full">
+ <div className="flex flex-1 items-center">
+ <label
+ htmlFor="name"
+ className="text-tertiary/[0.8] text-sm font-normal w-1/5"
+ >
+ Config Name
+ </label>
+ <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
+ <input
+ key={`${dbConfig?.id}-name`}
+ type="text"
+ name="name"
+ id="name"
+ className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
+ placeholder="db-config"
+ defaultValue={dbConfig?.name}
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-col mt-6 w-full">
+ <div className="flex flex-1 items-center">
+ <label
+ htmlFor="environment"
+ className="text-tertiary/[0.8] text-sm font-normal w-1/5"
+ >
+ Environment
+ </label>
+ <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
+ <input
+ key={`${dbConfig?.id}-environment`}
+ type="text"
+ name="environment"
+ id="environment"
+ className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
+ placeholder="production"
+ defaultValue={dbConfig?.environment}
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-col mt-6 w-full">
+ <div className="flex flex-1 items-center">
+ <label
+ htmlFor={DB_META_KEYS.url}
+ className="text-tertiary/[0.8] text-sm font-normal w-1/5"
+ >
+ Clickhouse Database url
+ </label>
+ <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
+ <input
+ key={`${dbConfig?.id}-${DB_META_KEYS.url}`}
+ type="text"
+ name={DB_META_KEYS.url}
+ id={DB_META_KEYS.url}
+ className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
+ placeholder="clickhouse://<user>:<password>@<host>:<port>/<database>[? key=value..]"
+ defaultValue={dbConfig?.meta[DB_META_KEYS.url]}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-6 flex items-center justify-end border-t border-secondary w-full py-2 gap-3">
+ <button
+ type="submit"
+ className={`rounded-sm bg-primary/[0.9] px-5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-primary focus-visible:outline ${
+ isLoading ? "animate-pulse" : ""
+ }`}
+ >
+ {dbConfig?.id ? "Update" : "Save"}
+ </button>
+ </div>
+ </form>
+ );
+}
+
+const ADD_NEW_ID = "ADD_NEW_ID";
+
+function DatabaseList({
+ dbConfigs,
+ successCb,
+ isLoadingList,
+}: {
+ dbConfigs: DBConfig[];
+ successCb: () => void;
+ isLoadingList: boolean;
+}) {
+ const { fireRequest, isLoading } = useFetchWrapper();
+ const [selectedDBConfigId, setSelectedDBConfigId] = useState<string>(
+ dbConfigs[0]?.id || ADD_NEW_ID
+ );
+
+ const dbConfigByKey = keyBy(dbConfigs, "id");
+
+ const onClickDB: MouseEventHandler<HTMLElement> = (event) => {
+ const { itemId = "" } = (
+ (event.target as HTMLElement).closest("li") as HTMLLIElement
+ ).dataset;
+ setSelectedDBConfigId(itemId);
+ };
+
+ const onClickDelete: MouseEventHandler<SVGSVGElement> = (event) => {
+ event.stopPropagation();
+ const { itemId = "" } = (
+ (event.target as SVGSVGElement).closest("li") as HTMLLIElement
+ ).dataset;
+
+ if (itemId)
+ fireRequest({
+ requestType: "DELETE",
+ url: `/api/db-config/${itemId}`,
+ responseDataKey: "data",
+ successCb,
+ });
+ };
+
+ const onClickSetCurrent: MouseEventHandler<HTMLDivElement> = (event) => {
+ event.stopPropagation();
+ const { itemId = "" } = (
+ (event.target as HTMLDivElement).closest("li") as HTMLLIElement
+ ).dataset;
+
+ if (itemId) {
+ toast.loading(
+ `Db config: ${dbConfigByKey[itemId].name} setting active!`,
+ {
+ id: "db-config-current",
+ }
+ );
+ fireRequest({
+ requestType: "POST",
+ url: `/api/db-config/current/${itemId}`,
+ responseDataKey: "data",
+ successCb: () => {
+ successCb();
+ toast.success(
+ `Db config: ${dbConfigByKey[itemId].name} set active!`,
+ {
+ id: "db-config-current",
+ }
+ );
+ },
+ failureCb: (err?: string) => {
+ toast.error(
+ err ||
+ `Db config: ${dbConfigByKey[itemId].name} setting active failed!`,
+ {
+ id: "db-config-current",
+ }
+ );
+ },
+ });
+ }
+ };
+
+ const items: SideTabItemProps[] = dbConfigs.map((dbConfig) => ({
+ id: dbConfig.id,
+ name: dbConfig.name,
+ badge: dbConfig.environment,
+ isCurrent: !!dbConfig.isCurrent,
+ enableActiveChange: true,
+ enableDeletion: true,
+ }));
+
+ items.push({
+ id: ADD_NEW_ID,
+ name: "Add New",
+ });
+
+ return (
+ <div
+ className={`flex flex-1 h-full border-t border-secondary relative ${isLoading}`}
+ >
+ <SideTabs
+ items={items}
+ onClickTab={onClickDB}
+ selectedTabId={selectedDBConfigId}
+ onClickItemChangeActive={onClickSetCurrent}
+ onClickItemDelete={onClickDelete}
+ />
+ <div className="flex flex-1 w-full h-full">
+ <ModifyDatabaseConfig
+ dbConfig={dbConfigByKey[selectedDBConfigId]}
+ successCb={successCb}
+ />
+ </div>
+ {(isLoading || isLoadingList) && (
+ <div className="flex absolute w-full left-0 top-0 h-full bg-secondary/[0.1] animate-pulse z-10" />
+ )}
+ </div>
+ );
+}
+
+export default function Database() {
+ const { data, fireRequest, isFetched, isLoading } = useFetchWrapper();
+
+ const fetchData = async () => {
+ fireRequest({
+ requestType: "GET",
+ url: "/api/db-config",
+ responseDataKey: "data",
+ });
+ };
+
+ useEffect(() => {
+ fetchData();
+ }, []);
+
+ return !isFetched ? (
+ <div className="flex items-center justify-center w-full h-full bg-secondary text-primary animate-pulse">
+ Loading...
+ </div>
+ ) : (
+ <DatabaseList
+ dbConfigs={(data as DBConfig[]) || []}
+ successCb={fetchData}
+ isLoadingList={isLoading}
+ />
+ );
+}
diff --git a/src/client/src/app/(playground)/settings/page.tsx b/src/client/src/app/(playground)/settings/page.tsx
new file mode 100644
index 00000000..50948396
--- /dev/null
+++ b/src/client/src/app/(playground)/settings/page.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+import { Tab } from "@headlessui/react";
+import { useSearchParams } from "next/navigation";
+import { ReactNode } from "react";
+import Database from "./database";
+import Profile from "./profile";
+
+type TabsObjectType = Record<
+ "profile" | "database",
+ {
+ title: string;
+ component: ReactNode;
+ }
+>;
+
+type KeyofTabsObjectType = keyof TabsObjectType;
+
+const tabsObject: TabsObjectType = {
+ profile: {
+ title: "Profile",
+ component: <Profile />,
+ },
+ database: {
+ title: "Database",
+ component: <Database />,
+ },
+};
+
+export default function Settings() {
+ const tabs = Object.keys(tabsObject) as Array<KeyofTabsObjectType>;
+ const search = useSearchParams();
+ const selectedTabIndex = tabs.indexOf(
+ (search.get("tab") || "") as KeyofTabsObjectType
+ );
+
+ return (
+ <div className="flex flex-col w-full flex-1 overflow-auto relative">
+ <Tab.Group defaultIndex={selectedTabIndex}>
+ <Tab.List className="flex space-x-1 bg-white sticky top-0 z-20">
+ {tabs.map((item) => (
+ <Tab
+ key={item}
+ className={({ selected }) =>
+ `w-auto py-2 px-3 text-sm font-medium leading-5 outline-none border-b-2 ${
+ selected
+ ? "text-primary border-primary"
+ : "text-tertiary/[0.3] border-white"
+ }`
+ }
+ >
+ {tabsObject[item].title}
+ </Tab>
+ ))}
+ </Tab.List>
+ <Tab.Panels className="flex flex-1 overflow-hidden w-full">
+ {tabs.map((item) => (
+ <Tab.Panel
+ key={item}
+ className={`flex-1 rounded-xl bg-white outline-none relative`}
+ >
+ {tabsObject[item].component}
+ </Tab.Panel>
+ ))}
+ </Tab.Panels>
+ </Tab.Group>
+ </div>
+ );
+}
diff --git a/src/client/src/app/(playground)/settings/profile.tsx b/src/client/src/app/(playground)/settings/profile.tsx
new file mode 100644
index 00000000..db25b3e6
--- /dev/null
+++ b/src/client/src/app/(playground)/settings/profile.tsx
@@ -0,0 +1,193 @@
+import SideTabs, { SideTabItemProps } from "@/components/common/side-tabs";
+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import { noop } from "@/utils/noop";
+import { FormEventHandler, MouseEventHandler, useState } from "react";
+import toast from "react-hot-toast";
+
+const PROFILE_TOAST_ID = "profile-details";
+
+function ModifyProfileDetails() {
+ const { error, fireRequest, isLoading } = useFetchWrapper();
+
+ const modifyDetails: FormEventHandler<HTMLFormElement> = (event) => {
+ event.preventDefault();
+ const formElement = event.target as HTMLFormElement;
+
+ const bodyObject = {
+ currentPassword: (formElement.currentPassword as any)?.value,
+ newPassword: (formElement.newPassword as any)?.value,
+ name: (formElement.name as any)?.value,
+ };
+
+ if (
+ bodyObject.newPassword !== (formElement.confirmNewPassword as any)?.value
+ ) {
+ toast.loading("New password and Confirm new password does not match...", {
+ id: PROFILE_TOAST_ID,
+ });
+ return;
+ }
+
+ toast.loading("Modifying profile details...", {
+ id: PROFILE_TOAST_ID,
+ });
+
+ fireRequest({
+ body: JSON.stringify(bodyObject),
+ requestType: "POST",
+ url: "/api/user/profile",
+ responseDataKey: "data",
+ successCb: () => {
+ toast.success("Profile details updated!", {
+ id: PROFILE_TOAST_ID,
+ });
+ formElement.reset();
+ },
+ failureCb: (err?: string) => {
+ toast.error(err || "Profile details updation failed!", {
+ id: PROFILE_TOAST_ID,
+ });
+ },
+ });
+ };
+
+ return (
+ <form
+ className="flex flex-col w-full"
+ onSubmit={isLoading ? noop : modifyDetails}
+ >
+ <div className="flex flex-col relative flex-1 overflow-y-auto px-5 py-3">
+ <h2 className="text-base font-semibold text-tertiary sticky top-0 bg-white">
+ Update profile details
+ </h2>
+
+ <div className="flex flex-col mt-6 w-full">
+ <div className="flex flex-1 items-center">
+ <label
+ htmlFor="name"
+ className="text-tertiary/[0.8] text-sm font-normal w-1/5"
+ >
+ Profile Name
+ </label>
+ <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
+ <input
+ key="name"
+ type="text"
+ name="name"
+ id="name"
+ className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
+ placeholder="profile name"
+ defaultValue=""
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-col mt-6 w-full">
+ <div className="flex flex-1 items-center">
+ <label
+ htmlFor="currentPassword"
+ className="text-tertiary/[0.8] text-sm font-normal w-1/5"
+ >
+ Current Password
+ </label>
+ <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
+ <input
+ key="currentPassword"
+ type="password"
+ name="currentPassword"
+ id="currentPassword"
+ className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
+ placeholder="********"
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-col mt-6 w-full">
+ <div className="flex flex-1 items-center">
+ <label
+ htmlFor="newPassword"
+ className="text-tertiary/[0.8] text-sm font-normal w-1/5"
+ >
+ New Password
+ </label>
+ <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
+ <input
+ key="newPassword"
+ type="password"
+ name="newPassword"
+ id="newPassword"
+ className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
+ placeholder="********"
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-col mt-6 w-full">
+ <div className="flex flex-1 items-center">
+ <label
+ htmlFor="confirmNewPassword"
+ className="text-tertiary/[0.8] text-sm font-normal w-1/5"
+ >
+ Confirm New Password
+ </label>
+ <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
+ <input
+ key="confirmNewPassword"
+ type="password"
+ name="confirmNewPassword"
+ id="confirmNewPassword"
+ className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
+ placeholder="********"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-6 flex items-center justify-end border-t border-secondary w-full py-2 gap-3">
+ <button
+ type="submit"
+ className={`rounded-sm bg-primary/[0.9] px-5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-primary focus-visible:outline ${
+ isLoading ? "animate-pulse" : ""
+ }`}
+ >
+ Update
+ </button>
+ </div>
+ </form>
+ );
+}
+
+export default function Profile() {
+ const items: SideTabItemProps[] = [
+ {
+ id: "details",
+ name: "Details",
+ },
+ ];
+
+ const [selectedTabId, setSelectedTabId] = useState<string>(items[0].id);
+
+ const onClickDB: MouseEventHandler<HTMLElement> = (event) => {
+ const { itemId = "" } = (
+ (event.target as HTMLElement).closest("li") as HTMLLIElement
+ ).dataset;
+ setSelectedTabId(itemId);
+ };
+
+ return (
+ <div className="flex flex-1 h-full border-t border-secondary relative">
+ <SideTabs
+ items={items}
+ onClickTab={onClickDB}
+ selectedTabId={selectedTabId}
+ />
+ <div className="flex flex-1 w-full h-full">
+ {selectedTabId === "details" ? <ModifyProfileDetails /> : null}
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/src/app/api/api-key/[id]/route.ts b/src/client/src/app/api/api-key/[id]/route.ts
index 0c082766..bdaac3db 100644
--- a/src/client/src/app/api/api-key/[id]/route.ts
+++ b/src/client/src/app/api/api-key/[id]/route.ts
@@ -1,4 +1,4 @@
-import { deleteAPIKey } from "@/lib/api-key";
+import { deleteAPIKey } from "@/lib/doku/api-key";
export async function DELETE(_: Request, context: any) {
const { id } = context.params;
diff --git a/src/client/src/app/api/api-key/route.ts b/src/client/src/app/api/api-key/route.ts
index 92b97f24..8d5775a4 100644
--- a/src/client/src/app/api/api-key/route.ts
+++ b/src/client/src/app/api/api-key/route.ts
@@ -1,4 +1,4 @@
-import { generateAPIKey, getAPIKeys } from "@/lib/api-key";
+import { generateAPIKey, getAPIKeys } from "@/lib/doku/api-key";
export async function GET() {
const res: any = await getAPIKeys();
diff --git a/src/client/src/app/api/db-config/[id]/route.ts b/src/client/src/app/api/db-config/[id]/route.ts
new file mode 100644
index 00000000..f8925495
--- /dev/null
+++ b/src/client/src/app/api/db-config/[id]/route.ts
@@ -0,0 +1,12 @@
+import { deleteDBConfig } from "@/lib/db-config";
+import asaw from "@/utils/asaw";
+
+export async function DELETE(_: Request, context: any) {
+ const { id } = context.params;
+ const [err, res] = await asaw(deleteDBConfig(id));
+ if (err)
+ return Response.json(err, {
+ status: 400,
+ });
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/db-config/current/[id]/route.ts b/src/client/src/app/api/db-config/current/[id]/route.ts
new file mode 100644
index 00000000..acc117fa
--- /dev/null
+++ b/src/client/src/app/api/db-config/current/[id]/route.ts
@@ -0,0 +1,12 @@
+import { setCurrentDBConfig } from "@/lib/db-config";
+import asaw from "@/utils/asaw";
+
+export async function POST(_: Request, context: any) {
+ const { id } = context.params;
+ const [err, res] = await asaw(setCurrentDBConfig(id));
+ if (err)
+ return Response.json(err, {
+ status: 400,
+ });
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/db-config/route.ts b/src/client/src/app/api/db-config/route.ts
new file mode 100644
index 00000000..61c0f143
--- /dev/null
+++ b/src/client/src/app/api/db-config/route.ts
@@ -0,0 +1,31 @@
+import { getDBConfigByUser, upsertDBConfig } from "@/lib/db-config";
+import asaw from "@/utils/asaw";
+
+export async function GET() {
+ const [err, res]: any = await asaw(getDBConfigByUser());
+ if (err)
+ return Response.json(err, {
+ status: 400,
+ });
+
+ return Response.json(res);
+}
+
+export async function POST(request: Request) {
+ const formData = await request.json();
+ const id = formData.id;
+ const name = formData.name;
+ const environment = formData.environment;
+ const meta = formData.meta;
+
+ const [err, res]: any = await asaw(
+ upsertDBConfig({ name, environment, meta }, id)
+ );
+
+ if (err)
+ return Response.json(err, {
+ status: 400,
+ });
+
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/user/profile/route.ts b/src/client/src/app/api/user/profile/route.ts
new file mode 100644
index 00000000..6035771d
--- /dev/null
+++ b/src/client/src/app/api/user/profile/route.ts
@@ -0,0 +1,20 @@
+import { updateUserProfile } from "@/lib/user";
+import asaw from "@/utils/asaw";
+
+export async function POST(request: Request) {
+ const formData = await request.json();
+ const formObject = {
+ currentPassword: formData.currentPassword,
+ newPassword: formData.newPassword,
+ name: formData.name,
+ };
+
+ const [err, res]: any = await asaw(updateUserProfile(formObject));
+
+ if (err)
+ return Response.json(err, {
+ status: 400,
+ });
+
+ return Response.json(res);
+}
diff --git a/src/client/src/app/auth.ts b/src/client/src/app/auth.ts
index af3bdefa..12ad235f 100644
--- a/src/client/src/app/auth.ts
+++ b/src/client/src/app/auth.ts
@@ -4,7 +4,12 @@ import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import asaw from "@/utils/asaw";
-import { createNewUser, getUserByEmail, updateUser } from "@/lib/user";
+import {
+ createNewUser,
+ getUserByEmail,
+ isPasswordMatches,
+ updateUser,
+} from "@/lib/user";
import { compare } from "bcrypt-ts";
const prisma = new PrismaClient();
@@ -81,7 +86,7 @@ export const authOptions = {
getUserByEmail({ email: credentials.email, selectPassword: true })
);
if (!user || err) return err || "No such user exists!";
- const passwordsMatch = await compare(
+ const passwordsMatch = await isPasswordMatches(
credentials.password,
user.password
);
diff --git a/src/client/src/app/layout.tsx b/src/client/src/app/layout.tsx
index 0c7474c2..d4e32046 100644
--- a/src/client/src/app/layout.tsx
+++ b/src/client/src/app/layout.tsx
@@ -1,6 +1,13 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
+import { Toaster } from "react-hot-toast";
+import { COLORS } from "../../colors";
+import {
+ ArrowPathIcon,
+ CheckCircleIcon,
+ ExclamationCircleIcon,
+} from "@heroicons/react/24/outline";
const inter = Inter({ subsets: ["latin"] });
@@ -17,7 +24,43 @@ export default function RootLayout({
}) {
return (
<html lang="en">
- <body className={inter.className}>{children}</body>
+ <body className={inter.className}>
+ {children}
+ <Toaster
+ position="bottom-right"
+ reverseOrder={false}
+ gutter={8}
+ toastOptions={{
+ duration: 3000,
+ style: {
+ fontSize: "14px",
+ fontWeight: "normal",
+ borderRadius: "4px 4px 0px 0px",
+ },
+ error: {
+ icon: <ExclamationCircleIcon className="w-4 h-4 shrink-0" />,
+ style: {
+ background: COLORS.error,
+ color: COLORS.secondary,
+ },
+ },
+ success: {
+ icon: <CheckCircleIcon className="w-4 h-4 shrink-0" />,
+ style: {
+ background: COLORS.primary,
+ color: COLORS.secondary,
+ },
+ },
+ loading: {
+ icon: <ArrowPathIcon className="w-4 h-4 shrink-0" />,
+ style: {
+ background: COLORS.secondary,
+ color: COLORS.primary,
+ },
+ },
+ }}
+ />
+ </body>
</html>
);
}
diff --git a/src/client/src/components/(playground)/sidebar.tsx b/src/client/src/components/(playground)/sidebar.tsx
index 817345fe..5a27c79a 100644
--- a/src/client/src/components/(playground)/sidebar.tsx
+++ b/src/client/src/components/(playground)/sidebar.tsx
@@ -10,6 +10,7 @@ import {
} from "@heroicons/react/24/solid";
import Image from "next/image";
import { usePathname } from "next/navigation";
+import { WrenchScrewdriverIcon } from "@heroicons/react/24/outline";
type SidebarItemProps = {
className?: string;
@@ -43,6 +44,11 @@ const SIDEBAR_ITEMS: SidebarItemProps[] = [
text: "API keys",
link: "/api-keys",
},
+ {
+ icon: <WrenchScrewdriverIcon className={ICON_CLASSES} />,
+ text: "Settings",
+ link: "/settings",
+ },
];
const SIDEBAR_BOTTOM_ITEMS: SidebarItemProps[] = [
diff --git a/src/client/src/components/common/side-tabs.tsx b/src/client/src/components/common/side-tabs.tsx
new file mode 100644
index 00000000..5f18667a
--- /dev/null
+++ b/src/client/src/components/common/side-tabs.tsx
@@ -0,0 +1,80 @@
+import { CheckIcon, TrashIcon } from "@heroicons/react/24/outline";
+import { MouseEventHandler } from "react";
+
+export type SideTabItemProps = {
+ id: string;
+ name: string;
+ badge?: string;
+ isCurrent?: boolean;
+ enableDeletion?: boolean;
+ enableActiveChange?: boolean;
+};
+
+export type SideTabsProps = {
+ items: SideTabItemProps[];
+ onClickTab: MouseEventHandler<HTMLElement>;
+ selectedTabId: string;
+ onClickItemDelete?: MouseEventHandler<SVGSVGElement>;
+ onClickItemChangeActive?: MouseEventHandler<HTMLDivElement>;
+};
+
+export default function SideTabs({
+ items,
+ onClickTab,
+ selectedTabId,
+ onClickItemDelete,
+ onClickItemChangeActive,
+}: SideTabsProps) {
+ return (
+ <ul className="shrink-0 w-1/5 border-r border-secondary overflow-y-auto">
+ {items.map((item) => (
+ <li
+ key={item.id}
+ className={`flex flex-col p-2 text-sm cursor-pointer border-b border-secondary relative group hover:bg-secondary/[0.3] ${
+ selectedTabId === item.id
+ ? "bg-secondary/[0.5] text-primary"
+ : "bg-tertiary/[0.02] text-tertiary/[0.8]"
+ }`}
+ data-item-id={item.id}
+ onClick={onClickTab}
+ >
+ {selectedTabId === item.id && (
+ <span className="absolute h-full right-0 top-0 w-0.5 bg-primary" />
+ )}
+ <span className="text-ellipsis overflow-hidden whitespace-nowrap">
+ {item.name}
+ </span>
+ {item.badge && (
+ <span
+ className={`mt-1 space-x-1 px-3 py-1 rounded-full text-xs font-medium max-w-fit ${
+ selectedTabId === item.id
+ ? "bg-primary/[0.1] text-primary"
+ : "bg-tertiary/[0.1] text-tertiary/[0.5]"
+ }`}
+ >
+ {item.badge}
+ </span>
+ )}
+ {item.enableDeletion && onClickItemDelete && (
+ <TrashIcon
+ className="w-3 h-3 absolute right-2 top-2 hidden group-hover:inline text-tertiary/[0.6] hover:text-primary"
+ onClick={onClickItemDelete}
+ />
+ )}
+ {item.enableActiveChange && onClickItemChangeActive && (
+ <div
+ className={`flex items-center justify-center w-4 h-4 absolute right-2 bottom-2 border rounded-full cursor-pointer ${
+ item.isCurrent
+ ? "border-primary bg-primary text-white"
+ : "border-tertiary/[0.3]"
+ }`}
+ onClick={onClickItemChangeActive}
+ >
+ {item.isCurrent && <CheckIcon className="w-3 h-3" />}
+ </div>
+ )}
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/src/client/src/constants/dbConfig.ts b/src/client/src/constants/dbConfig.ts
new file mode 100644
index 00000000..0fd8a116
--- /dev/null
+++ b/src/client/src/constants/dbConfig.ts
@@ -0,0 +1,3 @@
+export const DB_META_KEYS = {
+ url: "databaseURL",
+};
diff --git a/src/client/src/lib/db-config.ts b/src/client/src/lib/db-config.ts
new file mode 100644
index 00000000..6db1df8a
--- /dev/null
+++ b/src/client/src/lib/db-config.ts
@@ -0,0 +1,177 @@
+import prisma from "./prisma";
+import { getCurrentUser } from "./session";
+import { DatabaseConfig } from "@prisma/client";
+
+export const getDBConfigByUser = async (currentOnly?: boolean) => {
+ const user = await getCurrentUser();
+
+ if (!user) throw new Error("Unauthorized user!");
+
+ if (currentOnly) {
+ const dbConfig = await prisma.databaseConfigUser.findFirst({
+ where: {
+ userId: user.id,
+ isCurrent: true,
+ },
+ select: {
+ databaseConfig: true,
+ },
+ });
+ return dbConfig?.databaseConfig;
+ }
+
+ const dbUserConfigs = await prisma.databaseConfigUser.findMany({
+ where: {
+ userId: user.id,
+ },
+ select: {
+ databaseConfigId: true,
+ isCurrent: true,
+ databaseConfig: true,
+ },
+ orderBy: {
+ databaseConfig: {
+ createdAt: "asc",
+ },
+ },
+ });
+
+ const dbConfigs = dbUserConfigs.map((dbConfig) => dbConfig.databaseConfig);
+ const currentConfig = dbUserConfigs.find((dbConfig) => dbConfig.isCurrent);
+ return dbConfigs.map((dbConfig) => ({
+ ...dbConfig,
+ isCurrent: currentConfig?.databaseConfigId === dbConfig?.id,
+ }));
+};
+
+export const getDBConfigById = async ({ id }: { id: string }) => {
+ return await prisma.databaseConfig.findUnique({
+ where: {
+ id,
+ },
+ });
+};
+
+export const upsertDBConfig = async (
+ {
+ environment,
+ name,
+ meta,
+ }: {
+ environment: string;
+ name: string;
+ meta: string;
+ },
+ id?: string
+) => {
+ if (!name) throw new Error("No name provided");
+ if (!meta) throw new Error("No meta details provided");
+
+ const user = await getCurrentUser();
+
+ if (!user) throw new Error("Unauthorized user!");
+
+ const existingDBName = await prisma.databaseConfig.findUnique({
+ where: {
+ name,
+ NOT: {
+ id,
+ },
+ },
+ });
+
+ if (existingDBName?.id) throw new Error("DB config Name already exists");
+
+ const whereObject: any = {};
+ if (id) whereObject.id = id;
+ else whereObject.name = name;
+
+ const dbConfig = await prisma.databaseConfig.upsert({
+ where: whereObject,
+ create: {
+ environment,
+ name,
+ meta,
+ createdByUserId: user.id,
+ },
+ update: {
+ environment,
+ name,
+ meta,
+ },
+ });
+
+ if (!id) {
+ const ifFirstDBConfigCreated = await prisma.databaseConfigUser.count({
+ where: {
+ userId: user.id,
+ },
+ });
+ await prisma.databaseConfigUser.create({
+ data: {
+ userId: user.id,
+ databaseConfigId: dbConfig.id,
+ isCurrent: !ifFirstDBConfigCreated,
+ },
+ });
+ }
+
+ return `${id ? "Updated" : "Added"} db details successfully`;
+};
+
+export async function deleteDBConfig(id: string) {
+ const user = await getCurrentUser();
+
+ if (!user) throw new Error("Unauthorized user!");
+
+ await prisma.databaseConfigUser.delete({
+ where: {
+ databaseConfigId_userId: {
+ userId: user.id,
+ databaseConfigId: id,
+ },
+ },
+ });
+
+ await prisma.databaseConfig.delete({
+ where: {
+ id,
+ },
+ });
+
+ return "Deleted successfully!";
+}
+
+export async function setCurrentDBConfig(id: string) {
+ const user = await getCurrentUser();
+
+ if (!user) throw new Error("Unauthorized user!");
+
+ const currentConfig = await getDBConfigByUser(true);
+
+ await prisma.databaseConfigUser.update({
+ where: {
+ databaseConfigId_userId: {
+ userId: user.id,
+ databaseConfigId: (currentConfig as DatabaseConfig).id,
+ },
+ },
+ data: {
+ isCurrent: false,
+ },
+ });
+
+ await prisma.databaseConfigUser.update({
+ where: {
+ databaseConfigId_userId: {
+ userId: user.id,
+ databaseConfigId: id,
+ },
+ },
+ data: {
+ isCurrent: true,
+ },
+ });
+
+ return "Current DB config set successfully!";
+}
diff --git a/src/client/src/lib/api-key.ts b/src/client/src/lib/doku/api-key.ts
similarity index 51%
rename from src/client/src/lib/api-key.ts
rename to src/client/src/lib/doku/api-key.ts
index e9333a60..61325b07 100644
--- a/src/client/src/lib/api-key.ts
+++ b/src/client/src/lib/doku/api-key.ts
@@ -1,7 +1,7 @@
import crypto from "crypto";
-import prisma from "./prisma";
import asaw from "@/utils/asaw";
import { normalizeAPIKeys } from "@/utils/api-key";
+import { API_KEY_TABLE_NAME, dataCollector } from "./common";
type GenerateAPIKeyProps = {
name: string;
@@ -9,21 +9,20 @@ type GenerateAPIKeyProps = {
export async function generateAPIKey(params: GenerateAPIKeyProps) {
const api_key = crypto.randomBytes(32).toString("hex");
- return await asaw(
- prisma.doku_apikeys.create({
- data: {
- name: params.name,
- api_key,
- },
- })
- );
+ return dataCollector(`INSERT INTO ${API_KEY_TABLE_NAME} (name, api_key)
+ VALUES ("${params.name}", "${api_key}");`);
}
export async function getAPIKeys() {
- const [, data] = await asaw(prisma.doku_apikeys.findMany());
+ const [, { data }] = await asaw(
+ dataCollector(`SELECT * from ${API_KEY_TABLE_NAME}`)
+ );
return normalizeAPIKeys(data);
}
export async function deleteAPIKey(id: string) {
- return await asaw(prisma.doku_apikeys.delete({ where: { id } }));
+ const [, { data }] = await asaw(
+ dataCollector(`DELETE FROM ${API_KEY_TABLE_NAME} WHERE id = ${id};`)
+ );
+ return data;
}
diff --git a/src/client/src/lib/doku/category.ts b/src/client/src/lib/doku/category.ts
index a2376e22..2acfc741 100644
--- a/src/client/src/lib/doku/category.ts
+++ b/src/client/src/lib/doku/category.ts
@@ -1,35 +1,36 @@
import { GENERATION_CATEGORIZATION } from "@/utils/generation";
-import { DokuParams, TABLE_NAME, dataCollector } from "./common";
+import { DokuParams, DATA_TABLE_NAME, dataCollector } from "./common";
export async function getResultGenerationByCategories(params: DokuParams) {
const { start, end } = params.timeLimit;
- const query = `
- SELECT
- category,
- STRING_AGG(DISTINCT endpoint, ' , ') AS endpoints,
- CAST(COUNT(*) AS INTEGER) AS count,
- ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER(), 2) AS percentage
- FROM
- (
- SELECT
- CASE
- WHEN endpoint LIKE 'openai.chat%' THEN '${GENERATION_CATEGORIZATION.chat}'
- WHEN endpoint LIKE 'openai.completions%' THEN '${GENERATION_CATEGORIZATION.chat}'
- WHEN endpoint LIKE 'anthropic.completions%' THEN '${GENERATION_CATEGORIZATION.chat}'
- WHEN endpoint LIKE 'cohere.summarize%' THEN '${GENERATION_CATEGORIZATION.chat}'
- WHEN endpoint LIKE 'cohere.generate%' THEN '${GENERATION_CATEGORIZATION.chat}'
- WHEN endpoint LIKE 'cohere.chat%' THEN '${GENERATION_CATEGORIZATION.chat}'
- WHEN endpoint LIKE '%embed%' THEN '${GENERATION_CATEGORIZATION.embed}'
- WHEN endpoint LIKE 'openai.images%' THEN '${GENERATION_CATEGORIZATION.image}'
- WHEN endpoint LIKE 'openai.audio%' THEN '${GENERATION_CATEGORIZATION.audio}'
- WHEN endpoint LIKE 'openai.fine_tuning%' THEN '${GENERATION_CATEGORIZATION.finetune}'
- END AS category,
- endpoint
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
- ) AS subquery
- GROUP BY category`;
+ const query = `SELECT
+ category,
+ arrayStringConcat(arrayDistinct(groupArray(endpoint)), ', ') AS endpoints,
+ CAST(COUNT(*) AS INTEGER) AS count,
+ ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS percentage
+FROM
+ (
+ SELECT
+ CASE
+ WHEN endpoint LIKE 'openai.chat%' THEN '${GENERATION_CATEGORIZATION.chat}'
+ WHEN endpoint LIKE 'anthropic.completions%' THEN '${GENERATION_CATEGORIZATION.chat}'
+ WHEN endpoint LIKE 'cohere.summarize%' THEN '${GENERATION_CATEGORIZATION.chat}'
+ WHEN endpoint LIKE 'cohere.generate%' THEN '${GENERATION_CATEGORIZATION.chat}'
+ WHEN endpoint LIKE 'cohere.chat%' THEN '${GENERATION_CATEGORIZATION.chat}'
+ WHEN endpoint LIKE '%embed%' THEN '${GENERATION_CATEGORIZATION.embed}'
+ WHEN endpoint LIKE 'openai.images%' THEN '${GENERATION_CATEGORIZATION.image}'
+ WHEN endpoint LIKE 'openai.audio%' THEN '${GENERATION_CATEGORIZATION.audio}'
+ WHEN endpoint LIKE 'openai.fine_tuning%' THEN '${GENERATION_CATEGORIZATION.finetune}'
+ END AS category,
+ endpoint
+ FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
+ ) AS subquery
+GROUP BY
+ category;
+
+ `;
return dataCollector(query);
}
diff --git a/src/client/src/lib/doku/clickhouse-client.ts b/src/client/src/lib/doku/clickhouse-client.ts
new file mode 100644
index 00000000..f0a13edf
--- /dev/null
+++ b/src/client/src/lib/doku/clickhouse-client.ts
@@ -0,0 +1,21 @@
+// clickhouseService.js
+import { parseClickHouseConnectionString } from "@/utils/parser";
+import { ClickHouseClient, createClient } from "@clickhouse/client";
+import { createPool, Pool } from "generic-pool";
+
+export default function createClickhousePool(
+ connectionString: string
+): Pool<ClickHouseClient> {
+ const connectionObject = parseClickHouseConnectionString(connectionString);
+ return createPool(
+ {
+ create: async () => createClient(connectionObject),
+ destroy: (client: ClickHouseClient) => client.close(),
+ },
+ {
+ max: 10, // Adjust based on your server capacity and requirements
+ min: 2, // Start with a minimum number of connections
+ idleTimeoutMillis: 30000, // Adjust based on your workload and server characteristics
+ }
+ );
+}
diff --git a/src/client/src/lib/doku/common.ts b/src/client/src/lib/doku/common.ts
index e1fe8845..7f6309d1 100644
--- a/src/client/src/lib/doku/common.ts
+++ b/src/client/src/lib/doku/common.ts
@@ -1,6 +1,11 @@
-import { Prisma, PrismaClient } from ".prisma/client";
+import { DatabaseConfig } from "@prisma/client";
+import { getDBConfigByUser } from "../db-config";
+import createClickhousePool from "./clickhouse-client";
+import { DB_META_KEYS } from "@/constants/dbConfig";
+import asaw from "@/utils/asaw";
-export const TABLE_NAME = "DOKU_LLM_DATA";
+export const DATA_TABLE_NAME = "DOKU_LLM_DATA";
+export const API_KEY_TABLE_NAME = "doku_apikeys";
export type TimeLimit = {
start: Date;
@@ -22,17 +27,25 @@ export type DokuRequestParams = DokuParams & {
limit?: number;
};
-const prisma = new PrismaClient();
-
-export type DataCollectorType = { err?: unknown; data: unknown };
+export type DataCollectorType = { err?: unknown; data?: unknown };
export async function dataCollector(query: string): Promise<DataCollectorType> {
+ const [err, dbConfig] = await asaw(getDBConfigByUser(true));
+ if (err) return { err, data: [] };
+ const clickhousePool = createClickhousePool(
+ ((dbConfig as DatabaseConfig)?.meta as Record<string, any>)?.[
+ DB_META_KEYS.url
+ ] || ""
+ );
+ const client = await clickhousePool.acquire();
+
try {
- const response = await prisma.$queryRaw`${Prisma.raw(query)}`;
- return { data: response };
- } catch (err) {
- console.trace(err);
- return { err, data: [] };
+ const result = await client.query({ query, format: "JSONEachRow" });
+ const data = await result.json();
+ return { data };
+ } catch (error: any) {
+ console.trace(error);
+ return { err: `ClickHouse Query Error: ${error.message}`, data: [] };
} finally {
- prisma.$disconnect();
+ clickhousePool.release(client);
}
}
diff --git a/src/client/src/lib/doku/cost.ts b/src/client/src/lib/doku/cost.ts
index 273f0573..7178187b 100644
--- a/src/client/src/lib/doku/cost.ts
+++ b/src/client/src/lib/doku/cost.ts
@@ -1,12 +1,12 @@
-import { DokuParams, TABLE_NAME, dataCollector } from "./common";
+import { DokuParams, DATA_TABLE_NAME, dataCollector } from "./common";
export async function getTotalCost(params: DokuParams) {
const { start, end } = params.timeLimit;
const query = `SELECT
- CAST(SUM(usagecost) AS DECIMAL) AS total_usage_cost
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'`;
+ sum(usageCost) AS total_usage_cost
+ FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')`;
return dataCollector(query);
}
@@ -15,9 +15,9 @@ export async function getAverageCost(params: DokuParams) {
const { start, end } = params.timeLimit;
const query = `SELECT
- CAST(AVG(usagecost) AS DECIMAL) AS average_usage_cost
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'`;
+ avg(usageCost) AS average_usage_cost
+ FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')`;
return dataCollector(query);
}
@@ -25,14 +25,16 @@ export async function getAverageCost(params: DokuParams) {
export async function getCostByApplication(params: DokuParams) {
const { start, end } = params.timeLimit;
- const query = `
- SELECT
- DISTINCT applicationname as applicationname,
- CAST(ROUND(SUM(usagecost)::numeric, 7) AS FLOAT) AS cost,
- SUM(usagecost) * 100.0 / SUM(usagecost) AS percentage
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
- GROUP BY applicationname`;
+ const query = `SELECT
+ applicationName,
+ sum(usageCost) AS cost,
+ 100.0 * sum(usageCost) / sum(sum(usageCost)) OVER () AS percentage
+ FROM
+ ${DATA_TABLE_NAME}
+ WHERE
+ time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
+ GROUP BY
+ applicationName;`;
return dataCollector(query);
}
@@ -40,13 +42,12 @@ export async function getCostByApplication(params: DokuParams) {
export async function getCostByEnvironment(params: DokuParams) {
const { start, end } = params.timeLimit;
- const query = `
- SELECT
+ const query = `SELECT
DISTINCT environment as environment,
- CAST(ROUND(SUM(usagecost)::numeric, 7) AS FLOAT) AS cost,
- SUM(usagecost) * 100.0 / SUM(usagecost) AS percentage
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
+ SUM(usageCost) AS cost,
+ SUM(usageCost) * 100.0 / SUM(usageCost) AS percentage
+ FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
GROUP BY environment`;
return dataCollector(query);
diff --git a/src/client/src/lib/doku/endpoint.ts b/src/client/src/lib/doku/endpoint.ts
index 12f60086..ed71b546 100644
--- a/src/client/src/lib/doku/endpoint.ts
+++ b/src/client/src/lib/doku/endpoint.ts
@@ -1,16 +1,19 @@
-import { DokuParams, TABLE_NAME, dataCollector } from "./common";
+import { DokuParams, DATA_TABLE_NAME, dataCollector } from "./common";
export async function getResultGenerationByEndpoint(params: DokuParams) {
const { start, end } = params.timeLimit;
const query = `
- SELECT
- SUBSTRING(endpoint FROM '^[^.]+') AS provider,
- CAST(COUNT(*) AS INTEGER) AS count,
- ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER(), 2) AS percentage
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
- GROUP BY provider`;
+ SELECT
+ substringIndex(endpoint, '.', 1) AS provider,
+ CAST(count(*) AS INTEGER) AS count,
+ round(100.0 * count(*) / sum(count(*)) OVER (), 2) AS percentage
+ FROM
+ ${DATA_TABLE_NAME}
+ WHERE
+ time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
+ GROUP BY endpoint;
+ `;
return dataCollector(query);
}
diff --git a/src/client/src/lib/doku/model.ts b/src/client/src/lib/doku/model.ts
index a004bd72..0b22c73e 100644
--- a/src/client/src/lib/doku/model.ts
+++ b/src/client/src/lib/doku/model.ts
@@ -1,5 +1,5 @@
import { differenceInDays, differenceInYears } from "date-fns";
-import { DokuParams, TABLE_NAME, dataCollector } from "./common";
+import { DokuParams, DATA_TABLE_NAME, dataCollector } from "./common";
export type ModelDokuParams = DokuParams & {
top: number;
@@ -8,13 +8,20 @@ export type ModelDokuParams = DokuParams & {
export async function getTopModels(params: ModelDokuParams) {
const { start, end } = params.timeLimit;
- const query = `
- SELECT model, CAST(COUNT(model) AS INTEGER) AS model_count, CAST(COUNT(*) AS INTEGER) AS total
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
- GROUP BY model
- ORDER BY model_count DESC
- LIMIT ${params.top}`;
+ const query = `SELECT
+ model,
+ CAST(COUNT(model) AS INTEGER) AS model_count,
+ CAST(COUNT(*) AS INTEGER) AS total
+ FROM
+ ${DATA_TABLE_NAME}
+ WHERE
+ time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
+ GROUP BY
+ model
+ ORDER BY
+ model_count DESC
+ LIMIT ${params.top};
+ `;
return dataCollector(query);
}
@@ -29,13 +36,18 @@ export async function getModelsPerTime(params: DokuParams) {
}
const query = `SELECT
- DISTINCT model AS model,
- CAST(COUNT(*) AS INTEGER) AS model_count,
- TO_CHAR(DATE_TRUNC('${dateTrunc}', time), 'YY/MM/DD HH24:MI') AS request_time
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
- GROUP BY model, request_time
- ORDER BY request_time`;
+ model,
+ CAST(COUNT(*) AS INTEGER) AS model_count,
+ formatDateTime(DATE_TRUNC('${dateTrunc}', time), '%Y/%m/%d %R') AS request_time
+ FROM
+ ${DATA_TABLE_NAME}
+ WHERE
+ time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
+ GROUP BY
+ model, request_time
+ ORDER BY
+ request_time;
+ `;
return dataCollector(query);
}
diff --git a/src/client/src/lib/doku/request.ts b/src/client/src/lib/doku/request.ts
index 4ec12fb4..293db776 100644
--- a/src/client/src/lib/doku/request.ts
+++ b/src/client/src/lib/doku/request.ts
@@ -1,5 +1,5 @@
import {
- TABLE_NAME,
+ DATA_TABLE_NAME,
DokuParams,
dataCollector,
DokuRequestParams,
@@ -18,11 +18,16 @@ export async function getRequestPerTime(params: DokuParams) {
const query = `SELECT
CAST(COUNT(endpoint) AS INTEGER) AS total,
- TO_CHAR(DATE_TRUNC('${dateTrunc}', time), 'YY/MM/DD HH24:MI') AS request_time
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
- GROUP BY request_time
- ORDER BY request_time`;
+ formatDateTime(DATE_TRUNC('${dateTrunc}', time), '%Y/%m/%d %R') AS request_time
+ FROM
+ ${DATA_TABLE_NAME}
+ WHERE
+ time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
+ GROUP BY
+ request_time
+ ORDER BY
+ request_time;
+ `;
return dataCollector(query);
}
@@ -32,8 +37,8 @@ export async function getTotalRequests(params: DokuParams) {
const query = `SELECT
CAST(COUNT(endpoint) AS INTEGER) AS total_requests
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'`;
+ FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')`;
return dataCollector(query);
}
@@ -42,9 +47,12 @@ export async function getAverageRequestDuration(params: DokuParams) {
const { start, end } = params.timeLimit;
const query = `SELECT
- CAST(AVG(requestduration) AS DECIMAL) AS average_duration
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'`;
+ AVG(requestDuration) AS average_duration
+ FROM
+ ${DATA_TABLE_NAME}
+ WHERE
+ time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}');
+ `;
return dataCollector(query);
}
@@ -55,17 +63,17 @@ export async function getRequestsConfig(params: DokuRequestParams) {
const select = [
endpoints && "ARRAY_AGG(DISTINCT endpoint) AS endpoints",
- maxUsageCost && "MAX(usagecost) AS maxUsageCost",
+ maxUsageCost && "MAX(usageCost) AS maxUsageCost",
models && "ARRAY_AGG(DISTINCT model) AS models",
totalRows && "CAST(COUNT(*) AS INTEGER) AS totalRows",
]
.filter(Boolean)
- .join(" , ");
+ .join(", ");
if (select.length === 0) return [];
- const query = `SELECT ${select} FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'`;
+ const query = `SELECT ${select} FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')`;
return dataCollector(query);
}
@@ -81,8 +89,8 @@ export async function getRequests(params: DokuRequestParams) {
((configValues as DataCollectorType)?.data as Array<any>)?.[0] || {};
}
- const query = `SELECT * FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
+ const query = `SELECT * FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
ORDER BY time
LIMIT ${limit}
OFFSET ${offset}`;
diff --git a/src/client/src/lib/doku/token.ts b/src/client/src/lib/doku/token.ts
index 48531933..39ec2a32 100644
--- a/src/client/src/lib/doku/token.ts
+++ b/src/client/src/lib/doku/token.ts
@@ -1,5 +1,5 @@
import { differenceInDays, differenceInYears } from "date-fns";
-import { DokuParams, TABLE_NAME, dataCollector } from "./common";
+import { DokuParams, DATA_TABLE_NAME, dataCollector } from "./common";
export type TOKEN_TYPE = "total" | "prompt" | "completion";
@@ -11,15 +11,15 @@ export async function getAverageTokensPerRequest(params: TokenParams) {
const { start, end } = params.timeLimit;
const query = `SELECT
- CAST(AVG(${
+ AVG(${
params.type === "total"
- ? "totaltokens"
+ ? "totalTokens"
: params.type === "prompt"
- ? "prompttokens"
- : "completiontokens"
- }) AS DECIMAL) AS total_tokens
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'`;
+ ? "promptTokens"
+ : "completionTokens"
+ }) AS total_tokens
+ FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')`;
return dataCollector(query);
}
@@ -34,12 +34,12 @@ export async function getTokensPerTime(params: DokuParams) {
}
const query = `SELECT
- CAST(SUM(totaltokens) AS INTEGER) AS totaltokens,
- CAST(SUM(prompttokens) AS INTEGER) AS prompttokens,
- CAST(SUM(completiontokens) AS INTEGER) AS completiontokens,
- TO_CHAR(DATE_TRUNC('${dateTrunc}', time), 'YY/MM/DD HH24:MI') AS request_time
- FROM ${TABLE_NAME}
- WHERE time >= '${start}' AND time <= '${end}'
+ CAST(SUM(totalTokens) AS INTEGER) AS totaltokens,
+ CAST(SUM(promptTokens) AS INTEGER) AS prompttokens,
+ CAST(SUM(completionTokens) AS INTEGER) AS completiontokens,
+ formatDateTime(DATE_TRUNC('${dateTrunc}', time), '%Y/%m/%d %R') AS request_time
+ FROM ${DATA_TABLE_NAME}
+ WHERE time >= parseDateTimeBestEffort('${start}') AND time <= parseDateTimeBestEffort('${end}')
GROUP BY request_time
ORDER BY request_time`;
diff --git a/src/client/src/lib/session.ts b/src/client/src/lib/session.ts
index e441c34d..67a92ce3 100644
--- a/src/client/src/lib/session.ts
+++ b/src/client/src/lib/session.ts
@@ -1,14 +1,20 @@
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/auth";
import asaw from "@/utils/asaw";
-import { User } from "next-auth";
import { getUserById } from "./user";
+import { User } from "@prisma/client";
-export async function getCurrentUser(): Promise<User | null> {
+export async function getCurrentUser({
+ selectPassword,
+}: {
+ selectPassword?: boolean;
+} = {}): Promise<User | null> {
const [, session] = await asaw(getServerSession(authOptions));
if (session?.user?.id) {
- const [, user] = await asaw(getUserById({ id: session.user.id }));
+ const [, user] = await asaw(
+ getUserById({ id: session.user.id, selectPassword })
+ );
return user ?? null;
}
diff --git a/src/client/src/lib/user.ts b/src/client/src/lib/user.ts
index 0dedf127..29337004 100644
--- a/src/client/src/lib/user.ts
+++ b/src/client/src/lib/user.ts
@@ -1,7 +1,21 @@
-import { User } from "@prisma/client";
import prisma from "./prisma";
import asaw from "@/utils/asaw";
-import { genSaltSync, hashSync } from "bcrypt-ts";
+import { compare, genSaltSync, hashSync } from "bcrypt-ts";
+import { getCurrentUser } from "./session";
+import { User } from "@prisma/client";
+
+const getHashedPassword = (password: string): string => {
+ const salt = genSaltSync(10);
+ const hash = hashSync(password, salt);
+ return hash;
+};
+
+export const isPasswordMatches = async (
+ password: string,
+ userPassword: string
+): Promise<boolean> => {
+ return await compare(password, userPassword);
+};
function exclude<User>(
user: User,
@@ -23,26 +37,35 @@ export const getUserByEmail = async ({
email?: string;
selectPassword?: boolean;
}) => {
- if (!email) return ["No email Provided"];
+ if (!email) throw new Error("No email Provided");
const user = await prisma.user.findUnique({
where: {
email,
},
});
- if (!user) null;
+ if (!user) throw new Error("No user with this email exists");
// @ts-expect-error
return exclude(user, selectPassword && []);
};
-export const getUserById = async ({ id }: { id?: string }) => {
+export const getUserById = async ({
+ id,
+ selectPassword = false,
+}: {
+ id?: string;
+ selectPassword?: boolean;
+}) => {
if (!id) return null;
- return await prisma.user.findUnique({
+ const user = await prisma.user.findUnique({
where: {
id,
},
});
+
+ // @ts-expect-error
+ return exclude(user, selectPassword && []);
};
export const createNewUser = async (
@@ -58,13 +81,12 @@ export const createNewUser = async (
const [, existingUser] = await asaw(getUserByEmail({ email }));
if (existingUser) throw new Error("User already exists! Please signin!");
- const salt = genSaltSync(10);
- const hash = hashSync(password, salt);
+ const hashedPassword = getHashedPassword(password);
let createdUser = await prisma.user.create({
data: {
email,
- password: hash,
+ password: hashedPassword,
},
});
@@ -90,3 +112,42 @@ export const updateUser = async ({
data,
});
};
+
+export const updateUserProfile = async ({
+ currentPassword,
+ newPassword,
+ name,
+}: {
+ currentPassword?: string;
+ newPassword?: string;
+ name?: string;
+}) => {
+ const user = await getCurrentUser({ selectPassword: true });
+
+ if (!user) throw new Error("Unauthorized user!");
+
+ const updatedUserObject: Partial<User> = {};
+
+ if (newPassword) {
+ if (!currentPassword)
+ throw new Error("Provide current password to update it to new one!");
+ const passwordsMatch = await isPasswordMatches(
+ currentPassword,
+ user.password || ""
+ );
+ if (!passwordsMatch) throw new Error("Wrong current password!");
+ updatedUserObject.password = getHashedPassword(newPassword);
+ }
+
+ if (name) {
+ updatedUserObject.name = name;
+ }
+
+ if (Object.keys(updatedUserObject).length === 0)
+ throw new Error("Nothing to update!");
+
+ return updateUser({
+ data: updatedUserObject,
+ where: { id: user.id },
+ });
+};
diff --git a/src/client/src/middleware.ts b/src/client/src/middleware.ts
index 4f8c4087..26d19226 100644
--- a/src/client/src/middleware.ts
+++ b/src/client/src/middleware.ts
@@ -65,5 +65,6 @@ export const config = {
"/dashboard",
"/api-keys",
"/requests",
+ "/settings",
],
};
diff --git a/src/client/src/utils/api-key.ts b/src/client/src/utils/api-key.ts
index 292d3954..35b0a7b5 100644
--- a/src/client/src/utils/api-key.ts
+++ b/src/client/src/utils/api-key.ts
@@ -1,10 +1,10 @@
-import { doku_apikeys } from "@prisma/client";
-
export function maskingKey(key: string) {
return key.slice(0, 3) + "..." + key.slice(-3);
}
-export function normalizeAPIKeys(params: doku_apikeys[] | null | undefined) {
+export function normalizeAPIKeys(
+ params: Partial<{ api_key: string }>[] | null | undefined
+) {
if (params?.length)
- return params.map((p) => ({ ...p, api_key: maskingKey(p.api_key) }));
-}
+ return params.map((p) => ({ ...p, api_key: maskingKey(p?.api_key || "") }));
+}
\ No newline at end of file
diff --git a/src/client/src/utils/api.ts b/src/client/src/utils/api.ts
index fbd14575..9bb70d61 100644
--- a/src/client/src/utils/api.ts
+++ b/src/client/src/utils/api.ts
@@ -8,7 +8,8 @@ export async function getData({ body, method = "POST", url }: GET_DATA) {
const res = await fetch(url, { body, method });
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
- throw new Error("Failed to fetch data");
+ const error = await res.json();
+ throw new Error(error);
}
return res.json();
diff --git a/src/client/src/utils/asaw.ts b/src/client/src/utils/asaw.ts
index 3e3c8c63..a6ea95b0 100644
--- a/src/client/src/utils/asaw.ts
+++ b/src/client/src/utils/asaw.ts
@@ -1,3 +1,5 @@
export default function asaw<T>(p: Promise<T>): Promise<(T | null)[] | [any]> {
- return p.then((result: T) => [null, result]).catch((error: any) => [error]);
+ return p
+ .then((result: T) => [null, result])
+ .catch((error: any) => [error.toString()]);
}
diff --git a/src/client/src/utils/hooks/useFetchWrapper.ts b/src/client/src/utils/hooks/useFetchWrapper.ts
index 98c0269b..8ba33637 100644
--- a/src/client/src/utils/hooks/useFetchWrapper.ts
+++ b/src/client/src/utils/hooks/useFetchWrapper.ts
@@ -4,7 +4,7 @@ import { deleteData, getData } from "@/utils/api";
type useFetchWrapperProps = {
body?: string;
- failureCb?: () => void;
+ failureCb?: (s?: string) => void;
url: string;
requestType: "GET" | "POST" | "DELETE";
responseDataKey?: string;
@@ -27,6 +27,7 @@ export default function useFetchWrapper() {
successCb,
}: useFetchWrapperProps) => {
setIsLoading(true);
+ setError(null);
try {
let response;
if (requestType === "GET" || requestType === "POST") {
@@ -41,12 +42,18 @@ export default function useFetchWrapper() {
});
}
- const finalResponse = get(response, responseDataKey, response);
- setData(finalResponse);
- if (typeof successCb === "function") successCb(finalResponse);
+ if (response.err) {
+ setError(response.err);
+ if (typeof failureCb === "function") failureCb(response.err);
+ } else {
+ const finalResponse = get(response, responseDataKey, response);
+ setData(finalResponse);
+ if (typeof successCb === "function") successCb(finalResponse);
+ }
} catch (error) {
- setError(error);
- if (typeof failureCb === "function") failureCb();
+ const updatedError = (error as any).toString().replaceAll("Error:", "");
+ setError(updatedError);
+ if (typeof failureCb === "function") failureCb(updatedError);
}
setIsLoading(false);
diff --git a/src/client/src/utils/parser.ts b/src/client/src/utils/parser.ts
new file mode 100644
index 00000000..9dc6e1dd
--- /dev/null
+++ b/src/client/src/utils/parser.ts
@@ -0,0 +1,45 @@
+interface ClickHouseConnectionInfo {
+ username: string;
+ password: string;
+ host: string;
+ database: string;
+ additional_headers: Record<string, string>;
+}
+
+export const parseClickHouseConnectionString = (
+ connectionString: string
+): ClickHouseConnectionInfo => {
+ const regex =
+ /clickhouse(?:\+(\w+))?:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/([^?]+)(?:\?([^*]+))?/;
+
+ const match = connectionString.match(regex);
+
+ if (!match) {
+ throw new Error("Invalid ClickHouse connection string format");
+ }
+
+ const [, , username, password, hostStr, portStr, database, queryParamsStr] =
+ match;
+
+ const port = parseInt(portStr, 10);
+
+ const additional_headers: Record<string, string> = {};
+ if (queryParamsStr) {
+ queryParamsStr.split("&").forEach((param) => {
+ const [key, value] = param.split("=");
+ additional_headers[key] = value;
+ });
+ }
+
+ const host = `${
+ additional_headers["protocol"] || "http"
+ }://${hostStr}:${port}`;
+
+ return {
+ username,
+ password,
+ host,
+ database,
+ additional_headers,
+ };
+};
diff --git a/src/client/tailwind.config.ts b/src/client/tailwind.config.ts
index a13e4820..ee4f3c78 100644
--- a/src/client/tailwind.config.ts
+++ b/src/client/tailwind.config.ts
@@ -1,4 +1,5 @@
import type { Config } from "tailwindcss";
+import { COLORS } from "./colors";
export default {
content: [
@@ -13,14 +14,7 @@ export default {
current: "currentColor",
extend: {
colors: {
- darkMode: {
- primary: "#0C120C",
- secondary: "#212738",
- tertiary: "#FFF4D8",
- },
- primary: "#F36C06",
- secondary: "#FFF4D8",
- tertiary: "#212738",
+ ...COLORS,
// light mode
tremor: {
brand: {