feat: implement local caching for vCon data

Persist clients, storage stats, and file lists in local cache to improve initial load performance. Added breadcrumb navigation to the AdminPageHeader.
This commit is contained in:
Team Dark Devil committed 2026-11-16 23:10:44 +06:00
1 parent b42029f67d
commit 1a1c19d7bb
25 files changed
+892 -342

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
import {
createAdminSessionToken,
getAdminSessionPayload,
getSessionCookieOptions,
} from "@/core/auth/adminSession";
import {
getAdminAccountInfo,
updateAdminAccount,
} from "@/core/auth/adminUsers";
import { NextRequest, NextResponse } from "next/server";
const SESSION_COOKIE = "datastack_admin_session";
const SESSION_SECONDS = 8 * 60 * 60;
function validEmail(email: string) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
export async function GET(request: NextRequest) {
const sessionSecret =
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
"datastack-admin-session-default-secret-32-chars";
const token = request.cookies.get(SESSION_COOKIE)?.value || "";
const session = await getAdminSessionPayload(token, sessionSecret);
if (!session) {
return NextResponse.json(
{ error: "Authentication required." },
{ status: 401 },
);
}
const account = await getAdminAccountInfo(session.email);
return NextResponse.json({
profile: {
email: account.email,
role: "Owner",
storageMode: account.storageMode,
createdAt: account.createdAt,
sessionExpiresAt: new Date(session.expiresAt).toISOString(),
},
});
}
export async function PUT(request: NextRequest) {
const sessionSecret =
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
"datastack-admin-session-default-secret-32-chars";
const token = request.cookies.get(SESSION_COOKIE)?.value || "";
const session = await getAdminSessionPayload(token, sessionSecret);
if (!session) {
return NextResponse.json(
{ error: "Authentication required." },
{ status: 401 },
);
}
try {
const body = await request.json();
const nextEmail =
typeof body.email === "string"
? body.email.trim().toLowerCase()
: session.email;
const currentPassword =
typeof body.currentPassword === "string" ? body.currentPassword : "";
const newPassword =
typeof body.newPassword === "string" ? body.newPassword : "";
if (!validEmail(nextEmail)) {
return NextResponse.json(
{ error: "Enter a valid email address." },
{ status: 400 },
);
}
if (!currentPassword) {
return NextResponse.json(
{ error: "Current password is required to save changes." },
{ status: 400 },
);
}
if (newPassword && (newPassword.length < 8 || newPassword.length > 256)) {
return NextResponse.json(
{ error: "New password must be between 8 and 256 characters." },
{ status: 400 },
);
}
const account = await getAdminAccountInfo(session.email);
const result = await updateAdminAccount({
currentEmail: account.email,
currentPassword,
nextEmail,
nextPassword: newPassword || undefined,
});
if (!result.ok) {
return NextResponse.json({ error: result.error }, { status: 401 });
}
const expiresAt = Date.now() + SESSION_SECONDS * 1000;
const nextToken = await createAdminSessionToken(
result.email,
sessionSecret,
expiresAt,
);
const response = NextResponse.json({
success: true,
profile: {
email: result.email,
role: "Owner",
storageMode: account.storageMode,
createdAt: account.createdAt,
sessionExpiresAt: new Date(expiresAt).toISOString(),
},
});
response.cookies.set(
SESSION_COOKIE,
nextToken,
getSessionCookieOptions(request, SESSION_SECONDS),
);
return response;
} catch {
return NextResponse.json(
{ error: "Unable to update profile." },
{ status: 400 },
);
}
}
+4 -4
View File
@@ -8,26 +8,26 @@ import { NewClientModal } from '@/components/sections/NewClientModal';
import { Button } from '@/components/ui/Button';
import { StatStrip } from '@/components/ui/StatStrip';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import { useCallback, useEffect, useMemo, useState } from 'react';
export default function ClientsPage() {
const { error } = useToast();
const [modalOpen, setModalOpen] = useState(false);
const [clients, setClients] = useState<ClientItem[]>([]);
const [clients, setClients] = useState<ClientItem[]>(() => getCached<ClientItem[]>('vcon:clients', []));
const [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState<ClientStatusFilter>('all');
const [now, setNow] = useState(0);
const [now, setNow] = useState(() => Date.now());
const fetchClients = useCallback(async () => {
const response = await fetch('/api/clients');
if (!response.ok) throw new Error('Unable to load clients');
const data = await response.json();
setClients(data.clients || []);
setClients(setCached('vcon:clients', data.clients || []));
}, []);
useEffect(() => {
fetchClients().catch(() => {
setClients([]);
error('Unable to load clients', 'Could not fetch registered clients.');
});
}, [error, fetchClients]);
+5
View File
@@ -0,0 +1,5 @@
import { ProfileWorkspace } from '@/components/sections/ProfileWorkspace';
export default function ProfilePage() {
return <ProfileWorkspace />;
}
+42 -36
View File
@@ -7,12 +7,16 @@ import { CodeBlock } from '@/components/ui/CodeBlock';
import { Select } from '@/components/ui/Input';
import { Panel } from '@/components/ui/Panel';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import { useEffect, useState } from 'react';
export default function SdkGuidePage() {
const { success } = useToast();
const [clients, setClients] = useState<any[]>([]);
const [selectedClientId, setSelectedClientId] = useState<string>('');
const [clients, setClients] = useState<any[]>(() => getCached<any[]>('vcon:clients', []));
const [selectedClientId, setSelectedClientId] = useState<string>(() => {
const cached = getCached<any[]>('vcon:clients', []);
return cached[0]?.clientId ?? '';
});
useEffect(() => {
async function loadClients() {
@@ -20,10 +24,10 @@ export default function SdkGuidePage() {
const res = await fetch('/api/clients');
if (res.ok) {
const data = await res.json();
const list = data.clients || [];
const list = setCached('vcon:clients', data.clients || []);
setClients(list);
if (list.length > 0) {
setSelectedClientId(list[0].clientId);
setSelectedClientId((prev) => prev || list[0].clientId);
}
}
} catch {
@@ -65,7 +69,7 @@ if client.connect():
};
return (
<section className="flex w-full flex-col gap-2.5">
<section className="w-full">
<AdminPageHeader
title="Python SDK"
actions={
@@ -80,38 +84,40 @@ if client.connect():
}
/>
<Card compact className="flex items-center justify-between bg-[var(--surface)] px-3 py-2 font-mono text-[11.5px]">
<span className="text-[var(--accent)]">pip install ./sdk-python</span>
<Button
size="xs"
variant="ghost"
icon="Copy"
onClick={() => copySnippet('pip install ./sdk-python', 'Pip command')}
/>
</Card>
<div className="flex max-w-[860px] flex-col gap-2.5">
<Card compact className="flex items-center justify-between bg-[var(--surface)] px-3 py-2 font-mono text-[11.5px]">
<span className="text-[var(--accent)]">pip install ./sdk-python</span>
<Button
size="xs"
variant="ghost"
icon="Copy"
onClick={() => copySnippet('pip install ./sdk-python', 'Pip command')}
/>
</Card>
<Panel
title="Client Snippet"
action={
clients.length > 0 ? (
<div className="w-[170px]">
<Select
compact
value={selectedClientId}
onChange={(e) => setSelectedClientId(e.target.value)}
>
{clients.map((c) => (
<option key={c.clientId} value={c.clientId}>
{c.clientId}
</option>
))}
</Select>
</div>
) : undefined
}
>
<CodeBlock>{pythonSnippet}</CodeBlock>
</Panel>
<Panel
title="Client Snippet"
action={
clients.length > 0 ? (
<div className="w-[170px]">
<Select
compact
value={selectedClientId}
onChange={(e) => setSelectedClientId(e.target.value)}
>
{clients.map((c) => (
<option key={c.clientId} value={c.clientId}>
{c.clientId}
</option>
))}
</Select>
</div>
) : undefined
}
>
<CodeBlock>{pythonSnippet}</CodeBlock>
</Panel>
</div>
</section>
);
}
+9 -5
View File
@@ -6,12 +6,16 @@ import { CodeBlock } from '@/components/ui/CodeBlock';
import { Select, Textarea } from '@/components/ui/Input';
import { Panel } from '@/components/ui/Panel';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import { useEffect, useState } from 'react';
export default function SimulatorPage() {
const { success, error } = useToast();
const [clients, setClients] = useState<any[]>([]);
const [selectedClient, setSelectedClient] = useState<string>('');
const [clients, setClients] = useState<any[]>(() => getCached<any[]>('vcon:clients', []));
const [selectedClient, setSelectedClient] = useState<string>(() => {
const cached = getCached<any[]>('vcon:clients', []);
return cached[0]?.clientId ?? '';
});
const [payloadText, setPayloadText] = useState<string>(
JSON.stringify(
{
@@ -34,9 +38,9 @@ export default function SimulatorPage() {
const res = await fetch('/api/clients');
if (res.ok) {
const data = await res.json();
const list = data.clients || [];
const list = setCached('vcon:clients', data.clients || []);
setClients(list);
if (list.length > 0) setSelectedClient(list[0].clientId);
if (list.length > 0) setSelectedClient((prev) => prev || list[0].clientId);
}
} catch {
// ignore
@@ -136,7 +140,7 @@ export default function SimulatorPage() {
}
/>
<div className="grid grid-cols-1 gap-2.5 xl:grid-cols-2">
<div className="grid grid-cols-1 gap-2.5 lg:grid-cols-2">
<Panel title="Payload" bodyClassName="flex flex-col gap-2.5 p-3">
<Select
compact
+5 -4
View File
@@ -15,12 +15,13 @@ import {
TableWrap,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import { useCallback, useEffect, useState } from 'react';
export default function StoragePage() {
const { success, error } = useToast();
const [stats, setStats] = useState<any>(null);
const [files, setFiles] = useState<any[]>([]);
const [stats, setStats] = useState<any>(() => getCached<any>('vcon:storage-stats', null));
const [files, setFiles] = useState<any[]>(() => getCached<any[]>('vcon:storage-files', []));
const [flushing, setFlushing] = useState(false);
const fetchStorageData = useCallback(async () => {
@@ -28,8 +29,8 @@ export default function StoragePage() {
const res = await fetch('/api/storage');
if (!res.ok) throw new Error('Unable to load storage partitions');
const data = await res.json();
setStats(data.stats);
setFiles(data.files || []);
setStats(setCached('vcon:storage-stats', data.stats));
setFiles(setCached('vcon:storage-files', data.files || []));
} catch {
error('Storage load failed', 'Could not load storage partitions.');
}