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

+3 -1
View File
@@ -15,6 +15,7 @@ import {
TableWrap,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import type { ClientCredentials, ClientItem } from './clients/types';
@@ -35,6 +36,7 @@ function relativeTime(timestamp: string | undefined, now: number) {
}
export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps) {
const router = useRouter();
const { success, error } = useToast();
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
const [confirmAction, setConfirmAction] = useState<{
@@ -160,7 +162,7 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
className="h-6 w-6 border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
title={`View events for ${client.clientId}`}
aria-label={`View events for ${client.clientId}`}
onClick={() => window.location.assign(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
onClick={() => router.push(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
/>
<Button
type="button"
+23 -29
View File
@@ -4,7 +4,7 @@ import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { Button } from '@/components/ui/Button';
import { ClientList, type ClientListItem } from '@/components/ui/ClientList';
import { Panel } from '@/components/ui/Panel';
import { StatCard } from '@/components/ui/StatCard';
import { StatStrip } from '@/components/ui/StatStrip';
import {
Table,
TableBody,
@@ -14,6 +14,7 @@ import {
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { getCached, setCached } from '@/lib/vconCache';
import Link from 'next/link';
import React, { useCallback, useEffect, useState } from 'react';
@@ -48,10 +49,10 @@ type StorageFile = {
};
export const DashboardOverview: React.FC = () => {
const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
const [events, setEvents] = useState<EventItem[]>([]);
const [clients, setClients] = useState<ClientListItem[]>([]);
const [files, setFiles] = useState<StorageFile[]>([]);
const [metrics, setMetrics] = useState<DashboardMetrics | null>(() => getCached<DashboardMetrics | null>('vcon:metrics', null));
const [events, setEvents] = useState<EventItem[]>(() => getCached<EventItem[]>('vcon:dashboard-events', []));
const [clients, setClients] = useState<ClientListItem[]>(() => getCached<ClientListItem[]>('vcon:clients', []));
const [files, setFiles] = useState<StorageFile[]>(() => getCached<StorageFile[]>('vcon:storage-files', []));
const [isRefreshing, setIsRefreshing] = useState(false);
const refresh = useCallback(async () => {
@@ -64,18 +65,22 @@ export const DashboardOverview: React.FC = () => {
fetch('/api/clients', { cache: 'no-store' }),
]);
if (metricsResponse.ok) setMetrics(await metricsResponse.json());
if (metricsResponse.ok) {
const nextMetrics = await metricsResponse.json();
setMetrics(setCached('vcon:metrics', nextMetrics));
}
if (eventsResponse.ok) {
const data = await eventsResponse.json();
setEvents(data.events ?? []);
setEvents(setCached('vcon:dashboard-events', data.events ?? []));
}
if (storageResponse.ok) {
const data = await storageResponse.json();
setFiles(data.files ?? []);
setFiles(setCached('vcon:storage-files', data.files ?? []));
if (data.stats) setCached('vcon:storage-stats', data.stats);
}
if (clientsResponse.ok) {
const data = await clientsResponse.json();
setClients(data.clients ?? []);
setClients(setCached('vcon:clients', data.clients ?? []));
}
} catch {
// Keep the last successful dashboard snapshot when one request fails.
@@ -131,27 +136,16 @@ export const DashboardOverview: React.FC = () => {
}
/>
<div className="mb-2.5 grid grid-cols-2 gap-2.5 xl:grid-cols-4">
<StatCard
label="Events today"
value={eventsToday.toLocaleString()}
/>
<StatCard
label="Active clients"
value={`${activeClients} / ${totalClients}`}
/>
<StatCard
label="Storage used"
value={storageValue}
unit={storageUnit}
/>
<StatCard
label="Stored rows"
value={totalRows.toLocaleString()}
/>
</div>
<StatStrip
items={[
{ label: 'Events today', value: eventsToday.toLocaleString() },
{ label: 'Active clients', value: `${activeClients} / ${totalClients}`, dot: activeClients > 0 ? 'ok' : 'off' },
{ label: 'Storage used', value: `${storageValue} ${storageUnit}` },
{ label: 'Stored rows', value: totalRows.toLocaleString() },
]}
/>
<div className="grid min-w-0 grid-cols-1 gap-2.5 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<div className="grid min-w-0 grid-cols-1 gap-2.5 lg:grid-cols-[minmax(0,1.85fr)_minmax(0,1fr)]">
<Panel
title="Recent events"
meta={`${events.length}`}
+3 -1
View File
@@ -16,6 +16,7 @@ import {
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
interface StreamEvent {
@@ -34,6 +35,7 @@ interface Client {
const PAGE_SIZE = 12;
export function DataBrowser() {
const router = useRouter();
const [events, setEvents] = useState<StreamEvent[]>([]);
const [clients, setClients] = useState<Client[]>([]);
const [total, setTotal] = useState(0);
@@ -150,7 +152,7 @@ export function DataBrowser() {
variant="primary"
size="xs"
icon="Download"
onClick={() => window.location.assign('/vcon/export')}
onClick={() => router.push('/vcon/export')}
>
Export CSV
</Button>
+16 -17
View File
@@ -7,7 +7,9 @@ import { Panel } from '@/components/ui/Panel';
import { Pill } from '@/components/ui/Pill';
import { StatStrip } from '@/components/ui/StatStrip';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import { Braces, FileText } from 'lucide-react';
import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
interface Client {
@@ -48,22 +50,18 @@ function relativeTime(value: string, now: number) {
export function ExportWorkspace() {
const { error, info } = useToast();
const [clients, setClients] = useState<Client[]>([]);
const [files, setFiles] = useState<StorageFile[]>([]);
const [clients, setClients] = useState<Client[]>(() => getCached<Client[]>('vcon:clients', []));
const [files, setFiles] = useState<StorageFile[]>(() => getCached<StorageFile[]>('vcon:storage-files', []));
const [selectedClient, setSelectedClient] = useState('all');
const [fromDate, setFromDate] = useState('');
const [toDate, setToDate] = useState('');
const [fromDate, setFromDate] = useState(() => dateString(new Date()));
const [toDate, setToDate] = useState(() => dateString(new Date()));
const [format, setFormat] = useState<ExportFormat>('csv');
const [preset, setPreset] = useState<RangePreset>('today');
const [loading, setLoading] = useState(true);
const [loading, setLoading] = useState(() => getCached<StorageFile[]>('vcon:storage-files', []).length === 0);
const [loadError, setLoadError] = useState('');
const [now, setNow] = useState(0);
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const today = dateString(new Date());
setFromDate(today);
setToDate(today);
Promise.all([
fetch('/api/clients').then(async (response) => {
if (!response.ok) throw new Error('Unable to load clients');
@@ -75,8 +73,9 @@ export function ExportWorkspace() {
}),
])
.then(([clientData, storageData]) => {
setClients(clientData.clients || []);
setFiles(storageData.files || []);
setClients(setCached('vcon:clients', clientData.clients || []));
setFiles(setCached('vcon:storage-files', storageData.files || []));
if (storageData.stats) setCached('vcon:storage-stats', storageData.stats);
setLoadError('');
})
.catch((fetchError) => {
@@ -164,7 +163,7 @@ export function ExportWorkspace() {
};
return (
<section className="mx-auto w-full max-w-[var(--console-width)]">
<section className="w-full">
<AdminPageHeader title="Export" />
<StatStrip
@@ -176,8 +175,8 @@ export function ExportWorkspace() {
]}
/>
<div className="grid grid-cols-1 items-start gap-2.5 xl:grid-cols-5">
<Panel title="Export builder" bodyClassName="flex flex-col gap-3 p-3" className="min-w-0 xl:col-span-3">
<div className="grid grid-cols-1 items-start gap-2.5 lg:grid-cols-5">
<Panel title="Export builder" bodyClassName="flex flex-col gap-3 p-3" className="min-w-0 lg:col-span-3">
<div className="flex flex-wrap items-center gap-1">
<span className="mr-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Range</span>
{([
@@ -241,9 +240,9 @@ export function ExportWorkspace() {
<Panel
title="Files"
action={<a href="/vcon/storage" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all</a>}
action={<Link href="/vcon/storage" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all</Link>}
bodyClassName="divide-y divide-[var(--border)]"
className="min-w-0 xl:col-span-2"
className="min-w-0 lg:col-span-2"
>
{loading ? (
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">Loading...</p>
+244
View File
@@ -0,0 +1,244 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { SettingsField, SettingsGroup } from '@/components/ui/SettingsLayout';
import { StatStrip } from '@/components/ui/StatStrip';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import Link from 'next/link';
import { useEffect, useState } from 'react';
interface AdminProfileData {
email: string;
role: string;
storageMode: string;
createdAt: string;
sessionExpiresAt: string;
}
const DEFAULT_PROFILE: AdminProfileData = {
email: 'admin@datastack.dev',
role: 'Owner',
storageMode: 'In-Memory',
createdAt: '',
sessionExpiresAt: '',
};
export function ProfileWorkspace() {
const { success, error } = useToast();
const [profile, setProfile] = useState<AdminProfileData>(() => getCached<AdminProfileData>('vcon:profile', DEFAULT_PROFILE));
const [email, setEmail] = useState(() => getCached<AdminProfileData>('vcon:profile', DEFAULT_PROFILE).email);
const [currentPassword, setCurrentPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [loading, setLoading] = useState(() => !getCached<boolean>('vcon:profile-loaded', false));
const [saving, setSaving] = useState(false);
const [signingOut, setSigningOut] = useState(false);
useEffect(() => {
fetch('/api/auth/profile', { credentials: 'include' })
.then(async (res) => {
if (!res.ok) throw new Error('Unable to load profile');
return res.json();
})
.then((data) => {
if (data.profile) {
setProfile(setCached('vcon:profile', data.profile));
setEmail(data.profile.email);
setCached('vcon:profile-loaded', true);
}
})
.catch(() => {
error('Profile load failed', 'Could not load administrator profile.');
})
.finally(() => setLoading(false));
}, [error]);
const handleSave = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const trimmedEmail = email.trim().toLowerCase();
if (!trimmedEmail) {
error('Validation error', 'Admin email is required.');
return;
}
if (!currentPassword) {
error('Validation error', 'Enter your current password to save changes.');
return;
}
if (newPassword && newPassword !== confirmPassword) {
error('Validation error', 'New password and confirmation do not match.');
return;
}
setSaving(true);
try {
const response = await fetch('/api/auth/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
email: trimmedEmail,
currentPassword,
newPassword: newPassword || undefined,
}),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Profile update failed');
setProfile(setCached('vcon:profile', data.profile));
setEmail(data.profile.email);
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
success('Profile updated', 'Administrator credentials updated.');
} catch (saveError) {
error('Update failed', saveError instanceof Error ? saveError.message : 'Unable to update profile');
} finally {
setSaving(false);
}
};
const handleSignOut = async () => {
setSigningOut(true);
try {
const response = await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include',
});
if (!response.ok) throw new Error('Unable to sign out');
window.location.assign('/vcon/login');
} catch {
error('Sign out failed', 'Please try again.');
setSigningOut(false);
}
};
return (
<section className="w-full">
<AdminPageHeader
title="Profile"
actions={
<>
<Link href="/vcon/settings">
<Button type="button" size="xs" variant="secondary" icon="Sliders">
Settings
</Button>
</Link>
<Button
type="button"
size="xs"
variant="danger"
icon="LogOut"
loading={signingOut}
onClick={handleSignOut}
>
Sign out
</Button>
</>
}
/>
<StatStrip
items={[
{ label: 'Administrator', value: profile.email },
{ label: 'Role', value: profile.role, dot: 'ok' },
{ label: 'Auth Store', value: profile.storageMode },
{
label: 'Session Expires',
value: profile.sessionExpiresAt
? new Date(profile.sessionExpiresAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
: 'Active',
},
]}
/>
<form onSubmit={handleSave} className="max-w-[780px] border border-[var(--border)] bg-[var(--surface)]">
<SettingsGroup title="Account identity">
<SettingsField label="Admin email">
<Input
compact
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
required
/>
</SettingsField>
<SettingsField label="Access role">
<Input
compact
value={profile.role}
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]"
/>
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Security & password">
<SettingsField label="Current password">
<Input
compact
type="password"
autoComplete="current-password"
placeholder="Required to confirm changes"
value={currentPassword}
onChange={(event) => setCurrentPassword(event.target.value)}
required
/>
</SettingsField>
<SettingsField label="New password">
<Input
compact
type="password"
autoComplete="new-password"
placeholder="Leave blank to keep current"
value={newPassword}
onChange={(event) => setNewPassword(event.target.value)}
/>
</SettingsField>
<SettingsField label="Confirm new password">
<Input
compact
type="password"
autoComplete="new-password"
placeholder="Repeat new password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
/>
</SettingsField>
</SettingsGroup>
<footer className="flex flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] bg-[var(--surface)] px-3 py-2">
<span className="text-[11px] text-[var(--text-muted)]">
{loading ? 'Loading profile...' : 'Confirm current password to update credentials'}
</span>
<div className="flex items-center gap-2">
<Button
type="button"
size="xs"
disabled={saving}
onClick={() => {
setEmail(profile.email);
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
}}
>
Reset
</Button>
<Button
type="submit"
variant="primary"
size="xs"
icon="Save"
loading={saving}
disabled={loading || saving}
>
Update profile
</Button>
</div>
</footer>
</form>
</section>
);
}
+34 -30
View File
@@ -6,6 +6,7 @@ import { FormSwitch } from '@/components/ui/Form';
import { Input } from '@/components/ui/Input';
import { SettingsField, SettingsGroup, SettingsTabs } from '@/components/ui/SettingsLayout';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import { useEffect, useMemo, useState } from 'react';
interface EditableSettings {
@@ -45,15 +46,15 @@ type TabId = (typeof TABS)[number]['id'];
export function SettingsWorkspace() {
const { success, error } = useToast();
const [settings, setSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
const [savedSettings, setSavedSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
const [settings, setSettings] = useState<EditableSettings>(() => getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS));
const [savedSettings, setSavedSettings] = useState<EditableSettings>(() => getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS));
const [activeTab, setActiveTab] = useState<TabId>('general');
const [jwtSecret, setJwtSecret] = useState('');
const [storagePath, setStoragePath] = useState('');
const [storagePath, setStoragePath] = useState(() => getCached<string>('vcon:storage-path', ''));
const [baseUrl, setBaseUrl] = useState('');
const [webSocketUrl, setWebSocketUrl] = useState('');
const [serverPort, setServerPort] = useState(4000);
const [loading, setLoading] = useState(true);
const [serverPort, setServerPort] = useState(() => getCached<number>('vcon:server-port', 4000));
const [loading, setLoading] = useState(() => !getCached<boolean>('vcon:settings-loaded', false));
const [saving, setSaving] = useState(false);
useEffect(() => {
@@ -85,10 +86,11 @@ export function SettingsWorkspace() {
enableIdempotency: Boolean(settingsData.settings.enableIdempotency ?? DEFAULT_SETTINGS.enableIdempotency),
autoPruneDays: Number(settingsData.settings.autoPruneDays ?? DEFAULT_SETTINGS.autoPruneDays),
};
setSettings(loaded);
setSettings(setCached('vcon:settings', loaded));
setSavedSettings(loaded);
setServerPort(Number((settingsData.settings as PublicSettings).serverPort ?? 4000));
setStoragePath(String(storageData.stats?.storageDirectory ?? ''));
setServerPort(setCached('vcon:server-port', Number((settingsData.settings as PublicSettings).serverPort ?? 4000)));
setStoragePath(setCached('vcon:storage-path', String(storageData.stats?.storageDirectory ?? '')));
setCached('vcon:settings-loaded', true);
})
.catch(() => {
error('Settings load failed', 'Using default runtime settings.');
@@ -128,7 +130,7 @@ export function SettingsWorkspace() {
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Settings update failed');
setSettings(normalized);
setSettings(setCached('vcon:settings', normalized));
setSavedSettings(normalized);
setJwtSecret('');
success('Settings saved', 'Runtime settings updated.');
@@ -145,19 +147,20 @@ export function SettingsWorkspace() {
};
return (
<section className="mx-auto w-full max-w-[var(--console-width)]">
<section className="w-full">
<AdminPageHeader title="Settings" />
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
<div className="max-w-[780px]">
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
<form onSubmit={saveSettings}>
<div
id={`settings-panel-${activeTab}`}
role="tabpanel"
aria-labelledby={`settings-tab-${activeTab}`}
className="border border-t-0 border-[var(--border)] bg-[var(--surface)]"
>
<>
<form onSubmit={saveSettings}>
<div
id={`settings-panel-${activeTab}`}
role="tabpanel"
aria-labelledby={`settings-tab-${activeTab}`}
className="border border-t-0 border-[var(--border)] bg-[var(--surface)]"
>
<>
{activeTab === 'general' && (
<>
<SettingsGroup title="Identity">
@@ -231,18 +234,19 @@ export function SettingsWorkspace() {
</SettingsField>
</SettingsGroup>
)}
</>
</div>
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-3 py-2">
<div className="flex flex-1 items-center gap-1.5 text-[11px] text-[var(--text-muted)]" role="status">
<span className={`h-1.5 w-1.5 ${isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'}`} />
{loading ? 'Loading' : isDirty ? 'Unsaved' : 'Saved'}
</>
</div>
<Button type="button" size="xs" disabled={!isDirty || saving} onClick={discardChanges}>Discard</Button>
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save</Button>
</footer>
</form>
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-3 py-2">
<div className="flex flex-1 items-center gap-1.5 text-[11px] text-[var(--text-muted)]" role="status">
<span className={`h-1.5 w-1.5 ${isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'}`} />
{loading ? 'Loading' : isDirty ? 'Unsaved' : 'Saved'}
</div>
<Button type="button" size="xs" disabled={!isDirty || saving} onClick={discardChanges}>Discard</Button>
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save</Button>
</footer>
</form>
</div>
</section>
);
}
+1
View File
@@ -4,4 +4,5 @@ export * from "./ClientsTable";
export * from "./DataBrowser";
export * from "./ExportWorkspace";
export * from "./NewClientModal";
export * from "./ProfileWorkspace";
export * from "./SettingsWorkspace";