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]: Events tracking on Posthog (#487)

Aman Agarwal24f2134492e4
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index d5017db8..cc1a9f0b 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.29.2"
+version = "1.29.3"
description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects"
authors = ["OpenLIT"]
repository = "https://github.com/openlit/openlit/tree/main/openlit/python"
diff --git a/sdk/python/src/openlit/__init__.py b/sdk/python/src/openlit/__init__.py
index 8356933d..2a2beacd 100644
--- a/sdk/python/src/openlit/__init__.py
+++ b/sdk/python/src/openlit/__init__.py
@@ -350,7 +350,8 @@ def get_prompt(url=None, name=None, api_key=None, prompt_id=None,
'version': version,
'shouldCompile': should_compile,
'variables': variables,
- 'metaProperties': meta_properties
+ 'metaProperties': meta_properties,
+ 'source': 'python-sdk'
}
# Remove None values from payload
@@ -401,6 +402,7 @@ def get_secrets(url=None, api_key=None, key=None, tags=None, should_set_env=None
payload = {
'key': key,
'tags': tags,
+ 'source': 'python-sdk'
}
# Remove None values from payload
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
index 3faf78e3..4ad45da5 100644
--- a/sdk/typescript/package.json
+++ b/sdk/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "openlit",
- "version": "1.3.0",
+ "version": "1.3.1",
"homepage": "https://github.com/openlit/openlit#readme",
"bugs": {
"url": "https://github.com/openlit/openlit/issues",
diff --git a/sdk/typescript/src/features/vault.ts b/sdk/typescript/src/features/vault.ts
index 1b672efb..fac52e83 100644
--- a/sdk/typescript/src/features/vault.ts
+++ b/sdk/typescript/src/features/vault.ts
@@ -1,3 +1,4 @@
+import OpenlitConfig from '../config';
import { OPENLIT_URL } from '../constant';
import { VaultOptions } from '../types';
@@ -6,12 +7,19 @@ export default class Vault {
const url = process.env.OPENLIT_URL || options.url || OPENLIT_URL;
const apiKey = process.env.OPENLIT_API_KEY || options.apiKey || '';
+ const metaProperties = {
+ applicationName: OpenlitConfig.applicationName,
+ environment: OpenlitConfig.environment,
+ };
+
try {
const vaultResponse = await fetch(`${url}/api/vault/get-secrets`, {
method: 'POST',
body: JSON.stringify({
key: options.key,
tags: options.tags,
+ metaProperties,
+ source: 'ts-sdk',
}),
headers: {
Authorization: `Bearer ${apiKey}`,
diff --git a/src/client/.env.example b/src/client/.env.example
index aa463223..23703c7e 100644
--- a/src/client/.env.example
+++ b/src/client/.env.example
@@ -13,4 +13,9 @@ NEXTAUTH_URL=http://localhost:3000/
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
-SQLITE_DATABASE_URL=
\ No newline at end of file
+SQLITE_DATABASE_URL=
+
+# TELEMETRY TRACKING
+TELEMETRY_ENABLED=true
+POSTHOG_API_KEY=phc_JiR0FxzxAYeV3gDoMUltOxjLa3r7RnogMHPVrjDzTR9
+POSTHOG_API_HOST=https://us.i.posthog.com
\ No newline at end of file
diff --git a/src/client/Dockerfile b/src/client/Dockerfile
index 5efa3b7f..0e0fdc0b 100644
--- a/src/client/Dockerfile
+++ b/src/client/Dockerfile
@@ -17,21 +17,24 @@ RUN npm install && npm run build
# Use a smaller image for production
FROM alpine
-RUN apk add --update nodejs npm
+RUN apk add --update nodejs npm curl grep sed
# Set the working directory in the container
WORKDIR /app/client
# Copy only necessary files from the builder stage
COPY --from=builder /app/client/.next ./.next
-# COPY --from=builder /app/client/node_modules ./node_modules
COPY --from=builder /app/client/package.json ./package.json
COPY --from=builder /app/client/package-lock.json ./package-lock.json
COPY --from=builder /app/client/public ./public
COPY --from=builder /app/client/prisma ./prisma
+# Fetch posthog creds
+COPY --from=builder /app/client/scripts/fetch-posthog-creds.sh ./fetch-posthog-creds.sh
+RUN chmod +x ./fetch-posthog-creds.sh
+
# Execute entrypoint script to generate NextAuth.js secret and run commands
-COPY --from=builder /app/client/entrypoint.sh ./entrypoint.sh
+COPY --from=builder /app/client/scripts/entrypoint.sh ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
# Installing extra packages
RUN apk --no-cache add bash openssl
diff --git a/src/client/next.config.js b/src/client/next.config.js
index 20b04e5f..0fd42cbb 100644
--- a/src/client/next.config.js
+++ b/src/client/next.config.js
@@ -1,5 +1,10 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
+ env: {
+ TELEMETRY_ENABLED: process.env.TELEMETRY_ENABLED,
+ POSTHOG_API_KEY: process.env.POSTHOG_API_KEY,
+ POSTHOG_API_HOST: process.env.POSTHOG_API_HOST,
+ },
images: {
remotePatterns: [
{
diff --git a/src/client/package-lock.json b/src/client/package-lock.json
index 958c975d..440285cc 100644
--- a/src/client/package-lock.json
+++ b/src/client/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "openlit",
- "version": "1.11.1",
+ "version": "1.11.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openlit",
- "version": "1.9.1",
+ "version": "1.11.1",
"dependencies": {
"@anthropic-ai/sdk": "^0.21.1",
"@clickhouse/client": "^1.1.0",
@@ -48,6 +48,8 @@
"next-auth": "^4.24.7",
"next-themes": "^0.3.0",
"openai": "^4.50.0",
+ "posthog-js": "^1.176.0",
+ "posthog-node": "^4.2.1",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
@@ -5017,6 +5019,16 @@
"node": ">=4"
}
},
+ "node_modules/axios": {
+ "version": "1.7.7",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz",
+ "integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==",
+ "dependencies": {
+ "follow-redirects": "^1.15.6",
+ "form-data": "^4.0.0",
+ "proxy-from-env": "^1.1.0"
+ }
+ },
"node_modules/axobject-query": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-3.2.1.tgz",
@@ -5473,6 +5485,16 @@
"toggle-selection": "^1.0.6"
}
},
+ "node_modules/core-js": {
+ "version": "3.38.1",
+ "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.38.1.tgz",
+ "integrity": "sha512-OP35aUorbU3Zvlx7pjsFdu1rGNnD4pgw/CWoYzRY3t2EzoVT7shKHY1dlAy3f41cGIO7ZDPQimhGFTlEYkG/Hw==",
+ "hasInstallScript": true,
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/core-js"
+ }
+ },
"node_modules/cosmiconfig": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz",
@@ -6644,6 +6666,11 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/fflate": {
+ "version": "0.4.8",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.4.8.tgz",
+ "integrity": "sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA=="
+ },
"node_modules/file-entry-cache": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz",
@@ -6709,6 +6736,25 @@
"integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==",
"dev": true
},
+ "node_modules/follow-redirects": {
+ "version": "1.15.9",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
+ "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/RubenVerborgh"
+ }
+ ],
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependenciesMeta": {
+ "debug": {
+ "optional": true
+ }
+ }
+ },
"node_modules/for-each": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz",
@@ -8768,6 +8814,29 @@
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="
},
+ "node_modules/posthog-js": {
+ "version": "1.176.0",
+ "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.176.0.tgz",
+ "integrity": "sha512-T5XKNtRzp7q6CGb7Vc7wAI76rWap9fiuDUPxPsyPBPDkreKya91x9RIsSapAVFafwD1AEin1QMczCmt9Le9BWw==",
+ "dependencies": {
+ "core-js": "^3.38.1",
+ "fflate": "^0.4.8",
+ "preact": "^10.19.3",
+ "web-vitals": "^4.2.0"
+ }
+ },
+ "node_modules/posthog-node": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-4.2.1.tgz",
+ "integrity": "sha512-l+fsjYEkTik3m/G0pE7gMr4qBJP84LhK779oQm6MBzhBGpd4By4qieTW+4FUAlNCyzQTynn3Nhsa50c0IELSxQ==",
+ "dependencies": {
+ "axios": "^1.7.4",
+ "rusha": "^0.8.14"
+ },
+ "engines": {
+ "node": ">=15.0.0"
+ }
+ },
"node_modules/preact": {
"version": "10.22.0",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.22.0.tgz",
@@ -8861,6 +8930,11 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/proxy-from-env": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
+ },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -9300,6 +9374,11 @@
"queue-microtask": "^1.2.2"
}
},
+ "node_modules/rusha": {
+ "version": "0.8.14",
+ "resolved": "https://registry.npmjs.org/rusha/-/rusha-0.8.14.tgz",
+ "integrity": "sha512-cLgakCUf6PedEu15t8kbsjnwIFFR2D4RfL+W3iWFJ4iac7z4B0ZI8fxy4R3J956kAI68HclCFGL8MPoUVC3qVA=="
+ },
"node_modules/safe-array-concat": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz",
@@ -10216,6 +10295,11 @@
"node": ">= 8"
}
},
+ "node_modules/web-vitals": {
+ "version": "4.2.4",
+ "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-4.2.4.tgz",
+ "integrity": "sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw=="
+ },
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
diff --git a/src/client/package.json b/src/client/package.json
index 0ace6132..a69f006e 100644
--- a/src/client/package.json
+++ b/src/client/package.json
@@ -1,6 +1,6 @@
{
"name": "openlit",
- "version": "1.11.1",
+ "version": "1.11.2",
"private": true,
"scripts": {
"dev": "next dev",
@@ -50,6 +50,8 @@
"next-auth": "^4.24.7",
"next-themes": "^0.3.0",
"openai": "^4.50.0",
+ "posthog-js": "^1.176.0",
+ "posthog-node": "^4.2.1",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prisma
index 3bc000c4..9af3918b 100644
--- a/src/client/prisma/schema.prisma
+++ b/src/client/prisma/schema.prisma
@@ -1,6 +1,6 @@
generator client {
provider = "prisma-client-js"
- binaryTargets = ["native", "linux-arm64-openssl-3.0.x"]
+ binaryTargets = ["native", "linux-arm64-openssl-3.0.x", "linux-musl-arm64-openssl-3.0.x"]
}
datasource db {
diff --git a/src/client/entrypoint.sh b/src/client/scripts/entrypoint.sh
similarity index 83%
rename from src/client/entrypoint.sh
rename to src/client/scripts/entrypoint.sh
index 95b2ee8a..6388bf1b 100755
--- a/src/client/entrypoint.sh
+++ b/src/client/scripts/entrypoint.sh
@@ -1,10 +1,17 @@
#!/bin/bash
+
+# Run fetching posthog creds
+set +e
+./fetch-posthog-creds.sh
set -e
# Generate and set NextAuth.js secret as an environment variable
export NEXTAUTH_SECRET=$(openssl rand -base64 32)
# Set NextAuth.js environment variables
+# Default Telemetry enabled, Set this to false to disable telemetry tracking
+echo "TELEMETRY_ENABLED=true" >> /etc/environment
+
echo "NEXTAUTH_SECRET=$NEXTAUTH_SECRET" >> /etc/environment
echo "NEXTAUTH_URL=http://localhost:3000" >> /etc/environment
echo "SQLITE_DATABASE_URL=${SQLITE_DATABASE_URL:-file:../data/data.db}" >> /etc/environment
diff --git a/src/client/scripts/fetch-posthog-creds.sh b/src/client/scripts/fetch-posthog-creds.sh
new file mode 100755
index 00000000..be44ed61
--- /dev/null
+++ b/src/client/scripts/fetch-posthog-creds.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+# Script to fetch PostHog credentials from Cloudflare Worker
+
+# Default values
+WORKER_URL=${1:-"https://workers.openlit.io/api/posthog"}
+
+POSTHOG_API_KEY="POSTHOG_API_KEY"
+
+# Function to display error messages
+error() {
+ echo "ERROR: $1" >&2
+ exit 1
+}
+
+# Validate inputs
+[ -z "$WORKER_URL" ] && error "Worker URL is required"
+
+# Check if curl is installed
+command -v curl >/dev/null 2>&1 || error "curl is required but not installed"
+
+echo "Fetching PostHog credentials from Cloudflare Worker..."
+
+# Make the API request
+response=$(curl -s -f \
+ -H "User-Agent: Docker-Build" \
+ -H "Content-Type: application/json" \
+ "${WORKER_URL}" 2>&1) || error "Failed to fetch credentials: $response"
+
+# Extract credentials using grep and sed since we no longer require jq
+POSTHOG_API_KEY=$(echo "$response" | grep -o '"POSTHOG_API_KEY":"[^"]*"' | sed 's/"POSTHOG_API_KEY":"\([^"]*\)"/\1/')
+POSTHOG_HOST=$(echo "$response" | grep -o '"POSTHOG_HOST":"[^"]*"' | sed 's/"POSTHOG_HOST":"\([^"]*\)"/\1/')
+
+# Validate required fields
+[ -z "$POSTHOG_API_KEY" ] && error "PostHog API Key not found in response"
+[ -z "$POSTHOG_HOST" ] && error "PostHog Host not found in response"
+
+# Update environment variables
+echo "POSTHOG_API_KEY=\"${POSTHOG_API_KEY}\"" >> /etc/environment
+echo "POSTHOG_HOST=\"${POSTHOG_HOST}\"" >> /etc/environment
+
+echo "Credentials successfully fetched and saved to /etc/environment"
\ No newline at end of file
diff --git a/src/client/src/app/(playground)/database-config/page.tsx b/src/client/src/app/(playground)/database-config/page.tsx
index c67c4382..c2960040 100644
--- a/src/client/src/app/(playground)/database-config/page.tsx
+++ b/src/client/src/app/(playground)/database-config/page.tsx
@@ -22,12 +22,15 @@ import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { isNil, keyBy } from "lodash";
import { MouseEventHandler, useCallback, useState } from "react";
import { toast } from "sonner";
+import { usePostHog } from "posthog-js/react";
+import { CLIENT_EVENTS } from "@/constants/events";
function ModifyDatabaseConfig({
dbConfig,
}: {
dbConfig?: DatabaseConfigWithActive;
}) {
+ const posthog = usePostHog();
const { fireRequest, isLoading } = useFetchWrapper();
const modifyDetails: FormBuilderEvent = useCallback(
@@ -60,16 +63,30 @@ function ModifyDatabaseConfig({
url: "/api/db-config",
responseDataKey: "data",
successCb: () => {
- fetchDatabaseConfigList();
+ fetchDatabaseConfigList((data: any[]) => {
+ posthog?.capture(CLIENT_EVENTS.DB_CONFIG_LIST, {
+ count: data.length,
+ });
+ });
toast.success("Db config updated!", {
id: "db-config-details",
});
if (!dbConfig?.id) formElement.reset();
+ posthog?.capture(
+ payload.id
+ ? CLIENT_EVENTS.DB_CONFIG_UPDATE_SUCCESS
+ : CLIENT_EVENTS.DB_CONFIG_ADD_SUCCESS
+ );
},
failureCb: (err?: string) => {
toast.error(err || "Db config updation failed!", {
id: "db-config-details",
});
+ posthog?.capture(
+ payload.id
+ ? CLIENT_EVENTS.DB_CONFIG_UPDATE_FAILURE
+ : CLIENT_EVENTS.DB_CONFIG_ADD_FAILURE
+ );
},
});
},
@@ -205,6 +222,7 @@ function DatabaseList({
dbConfigs: DatabaseConfigWithActive[];
isLoadingList: boolean;
}) {
+ const posthog = usePostHog();
const [selectedDBConfigId, setSelectedDBConfigId] = useState<
string | undefined
>();
@@ -248,7 +266,9 @@ function DatabaseList({
id: "db-config-current",
}
);
- changeActiveDatabaseConfig(itemId);
+ changeActiveDatabaseConfig(itemId, () => {
+ posthog?.capture(CLIENT_EVENTS.DB_CONFIG_ACTION_CHANGE);
+ });
}
};
diff --git a/src/client/src/app/(playground)/layout.tsx b/src/client/src/app/(playground)/layout.tsx
index b20e71e1..ba00a657 100644
--- a/src/client/src/app/(playground)/layout.tsx
+++ b/src/client/src/app/(playground)/layout.tsx
@@ -1,12 +1,14 @@
"use client";
import Sidebar from "@/components/(playground)/sidebar";
import Header from "@/components/(playground)/header";
-import { useEffect } from "react";
+import { useEffect, Suspense } from "react";
import { useRootStore } from "@/store";
import { getIsUserFetched } from "@/selectors/user";
import { fetchAndPopulateCurrentUserStore } from "@/helpers/user";
import ClickhouseConnectivityWrapper from "@/components/(playground)/clickhouse-connectivity-wrapper";
import { TooltipProvider } from "@/components/ui/tooltip";
+import CustomPostHogProvider from "@/components/(playground)/posthog";
+import NavigationEvents from "@/components/common/navigation-events";
export default function PlaygroundLayout({
children,
@@ -20,17 +22,22 @@ export default function PlaygroundLayout({
}, [isFetched]);
return (
- <TooltipProvider>
- <div className="flex h-screen w-full pl-[56px] overflow-hidden">
- <Sidebar />
- <div className="flex flex-col grow w-full">
- <Header />
- <main className="flex flex-col grow flex-1 items-start p-4 sm:px-6 overflow-hidden">
- <ClickhouseConnectivityWrapper />
- {children}
- </main>
+ <CustomPostHogProvider>
+ <TooltipProvider>
+ <div className="flex h-screen w-full pl-[56px] overflow-hidden">
+ <Sidebar />
+ <div className="flex flex-col grow w-full">
+ <Header />
+ <main className="flex flex-col grow flex-1 items-start p-4 sm:px-6 overflow-hidden">
+ <ClickhouseConnectivityWrapper />
+ {children}
+ </main>
+ </div>
</div>
- </div>
- </TooltipProvider>
+ </TooltipProvider>
+ <Suspense fallback={null}>
+ <NavigationEvents />
+ </Suspense>
+ </CustomPostHogProvider>
);
}
diff --git a/src/client/src/app/(playground)/openground/new/prompt-input.tsx b/src/client/src/app/(playground)/openground/new/prompt-input.tsx
index 7a5b2729..5ee81f21 100644
--- a/src/client/src/app/(playground)/openground/new/prompt-input.tsx
+++ b/src/client/src/app/(playground)/openground/new/prompt-input.tsx
@@ -1,5 +1,6 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
+import { CLIENT_EVENTS } from "@/constants/events";
import {
getEvaluatedResponse,
getPrompt,
@@ -10,9 +11,11 @@ import {
} from "@/selectors/openground";
import { useRootStore } from "@/store";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import { usePostHog } from "posthog-js/react";
import { toast } from "sonner";
export default function PromptInput() {
+ const posthog = usePostHog();
const { fireRequest } = useFetchWrapper();
const prompt = useRootStore(getPrompt);
const selectedProviders = useRootStore(getSelectedProviders);
@@ -49,11 +52,16 @@ export default function PromptInput() {
id: "evaluation",
});
setEvaluatedDataFunction(data);
+ posthog?.capture(CLIENT_EVENTS.OPENGROUND_EVALUATION_SUCCESS, {
+ providers: selectedProviders.map((i) => i.provider),
+ prompt,
+ });
},
failureCb: (err?: string) => {
toast.error(err || "Evaluation failed!", {
id: "evaluation",
});
+ posthog?.capture(CLIENT_EVENTS.OPENGROUND_EVALUATION_FAILURE);
},
});
};
diff --git a/src/client/src/app/(playground)/profile/page.tsx b/src/client/src/app/(playground)/profile/page.tsx
index 2230233c..f8f66965 100644
--- a/src/client/src/app/(playground)/profile/page.tsx
+++ b/src/client/src/app/(playground)/profile/page.tsx
@@ -3,10 +3,12 @@
import FormBuilder, {
FormBuilderEvent,
} from "@/components/common/form-builder";
+import { CLIENT_EVENTS } from "@/constants/events";
import { getUserDetails, setUser } from "@/selectors/user";
import { useRootStore } from "@/store";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { User } from "@prisma/client";
+import { usePostHog } from "posthog-js/react";
import { toast } from "sonner";
const PROFILE_TOAST_ID = "profile-details";
@@ -18,6 +20,7 @@ function ModifyProfileDetails({
user: User | null;
fetchUser: () => void;
}) {
+ const posthog = usePostHog();
const { fireRequest, isLoading } = useFetchWrapper();
const modifyDetails: FormBuilderEvent = (event) => {
@@ -54,11 +57,13 @@ function ModifyProfileDetails({
});
formElement.reset();
fetchUser();
+ posthog?.capture(CLIENT_EVENTS.PROFILE_UPDATE_SUCCESS);
},
failureCb: (err?: string) => {
toast.error(err || "Profile details updation failed!", {
id: PROFILE_TOAST_ID,
});
+ posthog?.capture(CLIENT_EVENTS.PROFILE_UPDATE_FAILURE);
},
});
};
diff --git a/src/client/src/app/(playground)/prompt-hub/[id]/page.tsx b/src/client/src/app/(playground)/prompt-hub/[id]/page.tsx
index 4d9f5e51..47944f16 100644
--- a/src/client/src/app/(playground)/prompt-hub/[id]/page.tsx
+++ b/src/client/src/app/(playground)/prompt-hub/[id]/page.tsx
@@ -267,9 +267,13 @@ export default function PromptHub() {
</div>
...
<div className="w-max">
- {formatDistance(versionItem.updatedAt, new Date(), {
- addSuffix: true,
- })}
+ {formatDistance(
+ new Date(versionItem.updatedAt),
+ new Date().toISOString().slice(0, -1),
+ {
+ addSuffix: true,
+ }
+ )}
</div>
</Link>
))}
diff --git a/src/client/src/app/api/prompt/get-compiled/route.ts b/src/client/src/app/api/prompt/get-compiled/route.ts
index ad66d003..012283b5 100644
--- a/src/client/src/app/api/prompt/get-compiled/route.ts
+++ b/src/client/src/app/api/prompt/get-compiled/route.ts
@@ -1,7 +1,10 @@
+import { SERVER_EVENTS } from "@/constants/events";
import getMessage from "@/constants/messages";
import { PromptCompiledInput } from "@/constants/prompts";
import { getCompiledPrompt } from "@/lib/platform/prompt/compiled";
+import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
+import { randomUUID } from "crypto";
export async function POST(request: Request) {
const authorizationHeader = request.headers.get("Authorization") || "";
@@ -15,6 +18,7 @@ export async function POST(request: Request) {
});
}
+ const start = Date.now();
const formData = await request.json();
const promptInput: PromptCompiledInput = {
@@ -29,6 +33,17 @@ export async function POST(request: Request) {
};
const [err, res]: any = await asaw(getCompiledPrompt(promptInput));
+ const end = Date.now();
+ PostHogServer.capture({
+ event: err
+ ? SERVER_EVENTS.PROMPT_SDK_FETCH_FAILURE
+ : SERVER_EVENTS.PROMPT_SDK_FETCH_SUCCESS,
+ distinctId: randomUUID(),
+ properties: {
+ downloadSource: formData.source,
+ responseTime: end - start,
+ },
+ });
return Response.json({
err,
diff --git a/src/client/src/app/api/vault/get-secrets/route.ts b/src/client/src/app/api/vault/get-secrets/route.ts
index c94ed0b4..28fdcb24 100644
--- a/src/client/src/app/api/vault/get-secrets/route.ts
+++ b/src/client/src/app/api/vault/get-secrets/route.ts
@@ -1,7 +1,10 @@
+import { SERVER_EVENTS } from "@/constants/events";
import getMessage from "@/constants/messages";
import { SecretGetFiltersWithApiKey } from "@/constants/vault";
import { getSecretsFromDatabaseId } from "@/lib/platform/vault";
+import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
+import { randomUUID } from "crypto";
export async function POST(request: Request) {
const authorizationHeader = request.headers.get("Authorization") || "";
@@ -15,6 +18,8 @@ export async function POST(request: Request) {
});
}
+ const start = Date.now();
+
const formData = await request.json();
const filters: SecretGetFiltersWithApiKey = {
@@ -24,6 +29,17 @@ export async function POST(request: Request) {
};
const [err, data]: any = await asaw(getSecretsFromDatabaseId(filters));
+ const end = Date.now();
+ PostHogServer.capture({
+ event: err
+ ? SERVER_EVENTS.VAULT_SECRET_SDK_FETCH_FAILURE
+ : SERVER_EVENTS.VAULT_SECRET_SDK_FETCH_SUCCESS,
+ distinctId: randomUUID(),
+ properties: {
+ downloadSource: formData.source,
+ responseTime: end - start,
+ },
+ });
return Response.json({
err,
diff --git a/src/client/src/components/(auth)/auth-form.tsx b/src/client/src/components/(auth)/auth-form.tsx
index a287cb1f..10b0eca3 100644
--- a/src/client/src/components/(auth)/auth-form.tsx
+++ b/src/client/src/components/(auth)/auth-form.tsx
@@ -9,6 +9,8 @@ import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { usePostHog } from "posthog-js/react";
+import { CLIENT_EVENTS } from "@/constants/events";
const errors = {
AccessDenied: "Access denied for this account.",
@@ -32,6 +34,7 @@ const SignInError = ({ error }: { error: keyof typeof errors }) => {
};
export function AuthForm({ type }: { type: "login" | "register" }) {
+ const posthog = usePostHog();
const searchParams = useSearchParams();
const callbackUrl: string =
(searchParams.get("callbackUrl") as string) || DEFAULT_LOGGED_IN_ROUTE;
@@ -49,6 +52,9 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
return;
}
+ posthog?.capture(
+ type === "login" ? CLIENT_EVENTS.LOGIN : CLIENT_EVENTS.REGISTER
+ );
window.location.replace(callbackUrl);
}
async function login(formData: FormData) {
@@ -94,6 +100,7 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
<div className="grid gap-2">
<Label htmlFor="email">Email</Label>
<Input
+ className="ph-no-capture"
id="email"
name="email"
type="email"
@@ -107,6 +114,7 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
<Label htmlFor="password">Password</Label>
</div>
<Input
+ className="ph-no-capture"
autoComplete="current-password"
id="password"
name="password"
@@ -115,7 +123,10 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
required
/>
</div>
- <Button type="submit" className="w-full bg-primary dark:bg-primary text-white dark:text-white hover:dark:bg-primary">
+ <Button
+ type="submit"
+ className="w-full bg-primary dark:bg-primary text-white dark:text-white hover:dark:bg-primary"
+ >
{type === "login" ? "Sign in" : "Sign Up"}
</Button>
</div>
diff --git a/src/client/src/components/(playground)/api-keys/generate.tsx b/src/client/src/components/(playground)/api-keys/generate.tsx
index a6f6f5e8..299a19b6 100644
--- a/src/client/src/components/(playground)/api-keys/generate.tsx
+++ b/src/client/src/components/(playground)/api-keys/generate.tsx
@@ -16,8 +16,11 @@ import {
import { FieldProps } from "@/components/common/form-field";
import { jsonStringify } from "@/utils/json";
import { useState } from "react";
+import { usePostHog } from "posthog-js/react";
+import { CLIENT_EVENTS } from "@/constants/events";
export default function Generate({ refresh }: { refresh: () => void }) {
+ const posthog = usePostHog();
const [isOpen, setIsOpen] = useState(false);
const { fireRequest: fireCreateRequest, isLoading: isCreating } =
useFetchWrapper();
@@ -45,11 +48,13 @@ export default function Generate({ refresh }: { refresh: () => void }) {
});
setIsOpen(false);
refresh();
+ posthog?.capture(CLIENT_EVENTS.API_KEY_ADD_SUCCESS);
},
failureCb: (err?: string) => {
toast.error(err || `Cannot connect to server!`, {
id: "api-key",
});
+ posthog?.capture(CLIENT_EVENTS.API_KEY_ADD_FAILURE);
},
});
};
diff --git a/src/client/src/components/(playground)/database-config-switch.tsx b/src/client/src/components/(playground)/database-config-switch.tsx
index 738387ed..0f36a2d9 100644
--- a/src/client/src/components/(playground)/database-config-switch.tsx
+++ b/src/client/src/components/(playground)/database-config-switch.tsx
@@ -12,16 +12,25 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import { usePostHog } from "posthog-js/react";
+import { CLIENT_EVENTS } from "@/constants/events";
export default function DatabaseConfigSwitch() {
+ const posthog = usePostHog();
const list = useRootStore(getDatabaseConfigList) || [];
const activeDatabase = list.find((item) => !!item.isCurrent);
const onClickItem = (id: string) => {
- changeActiveDatabaseConfig(id);
+ changeActiveDatabaseConfig(id, () => {
+ posthog?.capture(CLIENT_EVENTS.DB_CONFIG_ACTION_CHANGE);
+ });
};
useEffect(() => {
- fetchDatabaseConfigList();
+ fetchDatabaseConfigList((data: any[]) => {
+ posthog?.capture(CLIENT_EVENTS.DB_CONFIG_LIST, {
+ count: data.length,
+ });
+ });
}, []);
if (!activeDatabase) return null;
diff --git a/src/client/src/components/(playground)/header.tsx b/src/client/src/components/(playground)/header.tsx
index 99365d12..022910c4 100644
--- a/src/client/src/components/(playground)/header.tsx
+++ b/src/client/src/components/(playground)/header.tsx
@@ -11,10 +11,12 @@ import {
import { Button } from "@/components/ui/button";
import { Moon, Sun, User } from "lucide-react";
import { useRootStore } from "@/store";
-import { getUserDetails } from "@/selectors/user";
+import { getUserDetails, resetUser } from "@/selectors/user";
import useTheme from "@/utils/hooks/useTheme";
import Link from "next/link";
import RefreshRate from "./filter/refresh-rate";
+import { usePostHog } from "posthog-js/react";
+import { useEffect } from "react";
const ThemeToggleSwitch = () => {
const { toggleTheme } = useTheme();
@@ -32,9 +34,21 @@ const ThemeToggleSwitch = () => {
};
export default function Header() {
+ const posthog = usePostHog();
const pathname = usePathname();
- const onClickSignout = () => signOut();
const user = useRootStore(getUserDetails);
+ const resetUserFn = useRootStore(resetUser);
+ const onClickSignout = () => {
+ posthog?.reset();
+ signOut();
+ resetUserFn();
+ };
+
+ useEffect(() => {
+ if (user?.id) {
+ posthog?.identify(user.id);
+ }
+ }, [user]);
return (
<header className="flex h-[57px] items-center gap-1 border-b dark:border-stone-800 px-4 sm:px-6">
diff --git a/src/client/src/components/(playground)/posthog.tsx b/src/client/src/components/(playground)/posthog.tsx
new file mode 100644
index 00000000..886d2356
--- /dev/null
+++ b/src/client/src/components/(playground)/posthog.tsx
@@ -0,0 +1,28 @@
+import { PostHogConfig } from "posthog-js";
+import { PostHogProvider } from "posthog-js/react";
+import { ReactNode } from "react";
+
+const POSTHOG_OPTIONS: Partial<PostHogConfig> = {
+ api_host: process.env.POSTHOG_API_HOST,
+ // debug: process.env.NODE_ENV !== "production",
+ autocapture: false,
+};
+
+export default function CustomPostHogProvider({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ if (process.env.TELEMETRY_ENABLED) {
+ return (
+ <PostHogProvider
+ apiKey={process.env.POSTHOG_API_KEY}
+ options={POSTHOG_OPTIONS}
+ >
+ {children}
+ </PostHogProvider>
+ );
+ }
+
+ return children;
+}
diff --git a/src/client/src/components/(playground)/prompt-hub/form.tsx b/src/client/src/components/(playground)/prompt-hub/form.tsx
index 197a22c9..2cb5367f 100644
--- a/src/client/src/components/(playground)/prompt-hub/form.tsx
+++ b/src/client/src/components/(playground)/prompt-hub/form.tsx
@@ -10,11 +10,13 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
+import { CLIENT_EVENTS } from "@/constants/events";
import { PromptInput, PromptUpdate } from "@/constants/prompts";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { jsonParse } from "@/utils/json";
import { objectEntries } from "@/utils/object";
import { useRouter } from "next/navigation";
+import { usePostHog } from "posthog-js/react";
import { KeyboardEvent, useCallback, useState } from "react";
import { toast } from "sonner";
@@ -46,6 +48,7 @@ export default function PromptForm({
children: JSX.Element;
successCallback?: () => void;
}) {
+ const posthog = usePostHog();
const router = useRouter();
const [isOpen, setIsOpen] = useState(false);
const { fireRequest, isLoading } = useFetchWrapper();
@@ -81,6 +84,7 @@ export default function PromptForm({
id: "prompt-hub",
});
setIsOpen(false);
+ posthog?.capture(CLIENT_EVENTS.PROMPT_ADD_SUCCESS);
if (response?.data?.promptId) {
router.push(`/prompt-hub/${response?.data?.promptId}`);
}
@@ -92,6 +96,7 @@ export default function PromptForm({
toast.error(err || "Creation of prompt failed!", {
id: "prompt-hub",
});
+ posthog?.capture(CLIENT_EVENTS.PROMPT_ADD_FAILURE);
},
});
}, []);
@@ -133,6 +138,7 @@ export default function PromptForm({
id: "prompt-hub",
});
setIsOpen(false);
+ posthog?.capture(CLIENT_EVENTS.PROMPT_VERSION_ADD_SUCCESS);
if (response?.data?.promptId) {
router.push(
`/prompt-hub/${response?.data?.promptId}?version=${payload.version}`
@@ -146,6 +152,7 @@ export default function PromptForm({
toast.error(err || "Updation of prompt version failed!", {
id: "prompt-hub",
});
+ posthog?.capture(CLIENT_EVENTS.PROMPT_VERSION_ADD_FAILURE);
},
});
}, []);
diff --git a/src/client/src/components/(playground)/vault/form.tsx b/src/client/src/components/(playground)/vault/form.tsx
index 8828aa01..5729a62b 100644
--- a/src/client/src/components/(playground)/vault/form.tsx
+++ b/src/client/src/components/(playground)/vault/form.tsx
@@ -9,9 +9,11 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
+import { CLIENT_EVENTS } from "@/constants/events";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { jsonParse } from "@/utils/json";
import { isEmpty } from "lodash";
+import { usePostHog } from "posthog-js/react";
import { KeyboardEvent, useCallback, useState } from "react";
import { toast } from "sonner";
@@ -24,6 +26,7 @@ export default function SecretForm({
children: JSX.Element;
successCallback?: () => void;
}) {
+ const posthog = usePostHog();
const [isOpen, setIsOpen] = useState(false);
const { fireRequest, isLoading } = useFetchWrapper();
const upsertSecret: FormBuilderEvent = useCallback((event, formdata) => {
@@ -50,6 +53,11 @@ export default function SecretForm({
}
);
setIsOpen(false);
+ posthog?.capture(
+ payload.id
+ ? CLIENT_EVENTS.VAULT_SECRET_UPDATE_SUCCESS
+ : CLIENT_EVENTS.VAULT_SECRET_ADD_SUCCESS
+ );
if (typeof successCallback === "function") {
successCallback();
}
@@ -61,6 +69,11 @@ export default function SecretForm({
id: "vault",
}
);
+ posthog?.capture(
+ payload.id
+ ? CLIENT_EVENTS.VAULT_SECRET_UPDATE_SUCCESS
+ : CLIENT_EVENTS.VAULT_SECRET_ADD_SUCCESS
+ );
},
});
}, []);
diff --git a/src/client/src/components/common/form-field.tsx b/src/client/src/components/common/form-field.tsx
index 2ed3c772..e513e5aa 100644
--- a/src/client/src/components/common/form-field.tsx
+++ b/src/client/src/components/common/form-field.tsx
@@ -87,6 +87,7 @@ function FormTagsInputField(props: FieldProps) {
return (
<div className="grid grid-col-1 gap-2">
<Input
+ className="ph-no-capture"
key={
props.inputKey ||
`${props.fieldTypeProps.name}-${props.fieldTypeProps.defaultValue}`
@@ -98,6 +99,7 @@ function FormTagsInputField(props: FieldProps) {
{tags.map((tag, index) => (
<Fragment key={tag}>
<Input
+ className="ph-no-capture"
type="hidden"
name={`${props.fieldTypeProps.name}`}
value={tag}
@@ -149,6 +151,7 @@ function FormKeyValueField(props: FieldProps) {
{metaProperties.map((prop, index) => (
<div key={index} className="flex gap-2 items-center">
<Input
+ className="ph-no-capture"
placeholder={`${placeholder} Key`}
name={`${name}[${index}].key`}
value={prop.key}
@@ -156,6 +159,7 @@ function FormKeyValueField(props: FieldProps) {
onKeyDown={onKeyDownHandler}
/>
<Input
+ className="ph-no-capture"
placeholder={`${placeholder} Value`}
name={`${name}[${index}].value`}
value={prop.value}
@@ -163,6 +167,7 @@ function FormKeyValueField(props: FieldProps) {
onKeyDown={onKeyDownHandler}
/>
<Button
+ className="ph-no-capture"
onClick={() => removeMetaProperty(index)}
variant="ghost"
size="icon"
@@ -225,7 +230,7 @@ function FormRadioGroupField(props: FieldProps) {
defaultValue={fieldTypeProps.defaultValue as string}
name={fieldTypeProps.name}
ref={itemRef}
- className="grid grid-cols-4 gap-8 pt-2"
+ className="grid grid-cols-4 gap-8 pt-2 ph-no-capture"
>
{fieldTypeProps.options.map((option) => {
return (
@@ -236,7 +241,10 @@ function FormRadioGroupField(props: FieldProps) {
data-value={option.value}
key={option.value}
>
- <RadioGroupItem value={option.value} className="sr-only" />
+ <RadioGroupItem
+ value={option.value}
+ className="sr-only ph-no-capture"
+ />
<div className="space-y-1 bg-stone-100 dark:bg-stone-800 p-4">
<h4 className="text-sm font-semibold">{option.title}</h4>
<p className="text-sm">{option.subText}</p>
@@ -255,7 +263,7 @@ function FormRadioGroupField(props: FieldProps) {
function FormInputField(props: FieldProps) {
return (
<Input
- className="col-span-2"
+ className="col-span-2 ph-no-capture"
key={props.inputKey || `${name}-${props.fieldTypeProps.defaultValue}`}
{...(props.fieldTypeProps as InputProps)}
/>
@@ -265,7 +273,7 @@ function FormInputField(props: FieldProps) {
function FormTextareaField(props: FieldProps) {
return (
<Textarea
- className="col-span-2"
+ className="col-span-2 ph-no-capture"
key={props.inputKey || `${name}-${props.fieldTypeProps.defaultValue}`}
{...(props.fieldTypeProps as TextareaProps)}
/>
diff --git a/src/client/src/components/common/navigation-events.tsx b/src/client/src/components/common/navigation-events.tsx
new file mode 100644
index 00000000..63eaf3b5
--- /dev/null
+++ b/src/client/src/components/common/navigation-events.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { useEffect } from "react";
+import { usePathname, useSearchParams } from "next/navigation";
+import { usePostHog } from "posthog-js/react";
+import { CLIENT_EVENTS } from "@/constants/events";
+
+export default function NavigationEvents() {
+ const posthog = usePostHog();
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+
+ useEffect(() => {
+ const url = `${pathname}?${searchParams}`;
+ posthog?.capture(CLIENT_EVENTS.PAGE_VISITED, {
+ url,
+ });
+ }, [pathname, searchParams]);
+
+ return null;
+}
diff --git a/src/client/src/constants/events.ts b/src/client/src/constants/events.ts
new file mode 100644
index 00000000..be4660ed
--- /dev/null
+++ b/src/client/src/constants/events.ts
@@ -0,0 +1,42 @@
+export const CLIENT_EVENTS = {
+ // Page
+ PAGE_VISITED: "PAGE_VISITED",
+ // Auth
+ LOGIN: "USER_LOGIN",
+ REGISTER: "USER_REGISTER",
+ // Database config
+ DB_CONFIG_ADD_SUCCESS: "DB_CONFIG_ADD_SUCCESS",
+ DB_CONFIG_UPDATE_SUCCESS: "DB_CONFIG_UPDATE_SUCCESS",
+ DB_CONFIG_ADD_FAILURE: "DB_CONFIG_ADD_FAILURE",
+ DB_CONFIG_UPDATE_FAILURE: "DB_CONFIG_UPDATE_FAILURE",
+ DB_CONFIG_LIST: "DB_CONFIG_LIST",
+ DB_CONFIG_ACTION_CHANGE: "DB_CONFIG_ACTION_CHANGE",
+ // Profile
+ PROFILE_UPDATE_SUCCESS: "PROFILE_UPDATE_SUCCESS",
+ PROFILE_UPDATE_FAILURE: "PROFILE_UPDATE_FAILURE",
+ // API KEY
+ API_KEY_ADD_SUCCESS: "API_KEY_ADD_SUCCESS",
+ API_KEY_ADD_FAILURE: "API_KEY_ADD_FAILURE",
+ // Prompt
+ PROMPT_ADD_SUCCESS: "PROMPT_ADD_SUCCESS",
+ PROMPT_ADD_FAILURE: "PROMPT_ADD_FAILURE",
+ PROMPT_VERSION_ADD_SUCCESS: "PROMPT_VERSION_ADD_SUCCESS",
+ PROMPT_VERSION_ADD_FAILURE: "PROMPT_VERSION_ADD_FAILURE",
+ // Vault
+ VAULT_SECRET_ADD_SUCCESS: "VAULT_SECRET_ADD_SUCCESS",
+ VAULT_SECRET_UPDATE_SUCCESS: "VAULT_SECRET_UPDATE_SUCCESS",
+ VAULT_SECRET_ADD_FAILURE: "VAULT_SECRET_ADD_FAILURE",
+ VAULT_SECRET_UPDATE_FAILURE: "VAULT_SECRET_UPDATE_FAILURE",
+ // Openground
+ OPENGROUND_EVALUATION_SUCCESS: "OPENGROUND_EVALUATION_SUCCESS",
+ OPENGROUND_EVALUATION_FAILURE: "OPENGROUND_EVALUATION_FAILURE",
+};
+
+export const SERVER_EVENTS = {
+ // Prompt
+ PROMPT_SDK_FETCH_SUCCESS: "PROMPT_SDK_FETCH_SUCCESS",
+ PROMPT_SDK_FETCH_FAILURE: "PROMPT_SDK_FETCH_FAILURE",
+ // Vault
+ VAULT_SECRET_SDK_FETCH_SUCCESS: "VAULT_SECRET_SDK_FETCH_SUCCESS",
+ VAULT_SECRET_SDK_FETCH_FAILURE: "VAULT_SECRET_SDK_FETCH_FAILURE",
+};
diff --git a/src/client/src/helpers/database-config.ts b/src/client/src/helpers/database-config.ts
index 2cc19bbd..e7c1217b 100644
--- a/src/client/src/helpers/database-config.ts
+++ b/src/client/src/helpers/database-config.ts
@@ -4,7 +4,9 @@ import { deleteData, getData } from "@/utils/api";
import asaw from "@/utils/asaw";
import { toast } from "sonner";
-export const fetchDatabaseConfigList = async () => {
+export const fetchDatabaseConfigList = async (
+ successCb: (data: any[]) => void
+) => {
useRootStore.getState().databaseConfig.setIsLoading(true);
const [, data] = await asaw(
getData({
@@ -13,6 +15,7 @@ export const fetchDatabaseConfigList = async () => {
})
);
+ successCb(data || []);
useRootStore.getState().databaseConfig.setList(data || []);
};
@@ -35,7 +38,10 @@ export const pingActiveDatabaseConfig = async () => {
});
};
-export const changeActiveDatabaseConfig = async (databaseConfigId: string) => {
+export const changeActiveDatabaseConfig = async (
+ databaseConfigId: string,
+ successCb: () => void
+) => {
const [err, data] = await asaw(
getData({
method: "POST",
@@ -50,6 +56,7 @@ export const changeActiveDatabaseConfig = async (databaseConfigId: string) => {
return;
}
+ successCb();
const list = useRootStore.getState().databaseConfig.list || [];
const updatedList = list.reduce((acc: DatabaseConfigWithActive[], item) => {
if (item.id === databaseConfigId) acc.push({ ...item, isCurrent: true });
diff --git a/src/client/src/lib/posthog.ts b/src/client/src/lib/posthog.ts
new file mode 100644
index 00000000..6a846b36
--- /dev/null
+++ b/src/client/src/lib/posthog.ts
@@ -0,0 +1,36 @@
+import { consoleLog } from "@/utils/log";
+import { PostHog } from "posthog-node";
+
+type EventMessage = Parameters<PostHog["capture"]>[0];
+
+export default class PostHogServer {
+ static client: PostHog;
+ static createClient() {
+ this.client = new PostHog(process.env.POSTHOG_API_KEY!, {
+ host: process.env.POSTHOG_API_HOST,
+ flushAt: 1,
+ flushInterval: 0,
+ });
+ }
+
+ static capture(options: EventMessage) {
+ try {
+ if (process.env.TELEMETRY_ENABLED) {
+ if (!this.client) {
+ this.createClient();
+ }
+
+ this.client.capture({
+ ...options,
+ properties: {
+ ...(options.properties || {}),
+ isServer: true,
+ },
+ });
+ this.client.shutdown();
+ }
+ } catch (error) {
+ consoleLog("Error capturing telemetry events:", error);
+ }
+ }
+}
diff --git a/src/client/src/store/user.ts b/src/client/src/store/user.ts
index a7fe02b4..5532485f 100644
--- a/src/client/src/store/user.ts
+++ b/src/client/src/store/user.ts
@@ -21,6 +21,6 @@ export const userStoreSlice: UserStore = lens((setStore, getStore) => ({
setStore(() => ({
...getStore(),
details: undefined,
- isFetched: true,
+ isFetched: false,
})),
}));