chore: publish current DataStack updates

Publish the current application, design, and Phase 1 deployment updates. Excludes ignored personal notes, local MCP config, and generated TypeScript build info.
This commit is contained in:
i vib committed 2026-10-23 19:56:38 -07:00
1 parent d39d9f92f9
commit fcc4f4db2d
88 files changed
+21248 -2213

No files matched your search

+81 -368
View File
@@ -1,393 +1,106 @@
'use client';
import React, { useState, useEffect, useCallback } from 'react';
import { Card } from '@/components/ui/Card';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import type { ClientItem, ClientStatusFilter } from '@/components/sections/clients/types';
import { ClientsFilters } from '@/components/sections/ClientsFilters';
import { ClientsTable } from '@/components/sections/ClientsTable';
import { NewClientModal } from '@/components/sections/NewClientModal';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import { Icon } from '@/components/ui/Icon';
import {
TableWrap,
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
TableEmpty,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
interface ClientItem {
clientId: string;
name: string;
secret: string;
token: string;
rateLimit: number;
status: 'active' | 'revoked';
totalEvents: number;
lastActive?: string;
createdAt: string;
}
import { StatStrip } from '@/components/ui/StatStrip';
import { Plus } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
export default function ClientsPage() {
const { success, error, warning } = useToast();
const [modalOpen, setModalOpen] = useState(false);
const [clients, setClients] = useState<ClientItem[]>([]);
const [loading, setLoading] = useState(true);
// Modals
const [createModalOpen, setCreateModalOpen] = useState(false);
const [tokenModalOpen, setTokenModalOpen] = useState(false);
const [selectedClient, setSelectedClient] = useState<ClientItem | null>(null);
// Form State
const [newClientId, setNewClientId] = useState('');
const [newClientName, setNewClientName] = useState('');
const [newRateLimit, setNewRateLimit] = useState('100');
const [submitting, setSubmitting] = useState(false);
const [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState<ClientStatusFilter>('all');
const [now, setNow] = useState(0);
const fetchClients = useCallback(async () => {
try {
const res = await fetch('/api/clients');
if (res.ok) {
const data = await res.json();
setClients(data.clients || []);
}
} catch {
// ignore
} finally {
setLoading(false);
}
const response = await fetch('/api/clients');
if (!response.ok) throw new Error('Unable to load clients');
const data = await response.json();
setClients(data.clients || []);
}, []);
useEffect(() => {
fetchClients();
fetchClients().catch(() => setClients([]));
}, [fetchClients]);
const handleCreateClient = async (e: React.FormEvent) => {
e.preventDefault();
if (!newClientId.trim() || !newClientName.trim()) {
error('Validation Error', 'Client ID and Client Name are required');
return;
}
useEffect(() => {
const updateClock = () => setNow(Date.now());
updateClock();
const interval = setInterval(updateClock, 15_000);
return () => clearInterval(interval);
}, []);
setSubmitting(true);
try {
const res = await fetch('/api/clients', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: newClientId.trim(),
name: newClientName.trim(),
rateLimit: Number(newRateLimit) || 100,
}),
});
const visibleClients = useMemo(() => {
const query = search.trim().toLowerCase();
return clients.filter((client) => {
const matchesSearch = !query ||
client.clientId.toLowerCase().includes(query) ||
client.name.toLowerCase().includes(query);
const online = client.status === 'active' && Boolean(client.lastActive) &&
now - new Date(client.lastActive!).getTime() < 60_000;
const pending = client.status === 'active' && !client.lastActive;
const matchesStatus = statusFilter === 'all' ||
(statusFilter === 'online' && online) ||
(statusFilter === 'offline' && !online && !pending) ||
(statusFilter === 'pending' && pending);
return matchesSearch && matchesStatus;
});
}, [clients, now, search, statusFilter]);
if (res.ok) {
const data = await res.json();
success('Client Registered', `Client ${data.client.clientId} created successfully`);
setCreateModalOpen(false);
setNewClientId('');
setNewClientName('');
setNewRateLimit('100');
fetchClients();
// Open token modal immediately
setSelectedClient(data.client);
setTokenModalOpen(true);
} else {
const errData = await res.json();
error('Registration Failed', errData.error || 'Unknown error');
}
} catch (err: any) {
error('Error', err.message);
} finally {
setSubmitting(false);
}
};
const handleToggleStatus = async (client: ClientItem) => {
const newStatus = client.status === 'active' ? 'revoked' : 'active';
try {
const res = await fetch(`/api/clients/${client.clientId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: newStatus }),
});
if (res.ok) {
warning(
`Status Changed`,
`Client ${client.clientId} is now ${newStatus.toUpperCase()}`
);
fetchClients();
}
} catch (err: any) {
error('Update Failed', err.message);
}
};
const handleRegenerateToken = async (client: ClientItem) => {
try {
const res = await fetch(`/api/clients/${client.clientId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'regenerate_token' }),
});
if (res.ok) {
const data = await res.json();
success('Token Regenerated', `New JWT issued for ${client.clientId}`);
setSelectedClient(data.client);
setTokenModalOpen(true);
fetchClients();
}
} catch (err: any) {
error('Regeneration Failed', err.message);
}
};
const handleDeleteClient = async (client: ClientItem) => {
if (!confirm(`Are you sure you want to delete client '${client.clientId}'?`)) return;
try {
const res = await fetch(`/api/clients/${client.clientId}`, {
method: 'DELETE',
});
if (res.ok) {
success('Client Removed', `Client ${client.clientId} deleted`);
fetchClients();
}
} catch (err: any) {
error('Deletion Failed', err.message);
}
};
const copyToClipboard = (text: string, label: string) => {
navigator.clipboard.writeText(text);
success('Copied to Clipboard', `${label} copied`);
};
const onlineCount = clients.filter((client) =>
client.status === 'active' && client.lastActive &&
now - new Date(client.lastActive).getTime() < 60_000
).length;
const pendingCount = clients.filter((client) =>
client.status === 'active' && !client.lastActive
).length;
const offlineCount = clients.length - onlineCount - pendingCount;
return (
<div className="flex flex-col gap-4">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[var(--border)] pb-2">
<h1 className="text-[14px] font-semibold text-[var(--text)] tracking-tight">
Client SDKs
</h1>
<Button
size="xs"
variant="primary"
icon="Plus"
onClick={() => setCreateModalOpen(true)}
className="self-start sm:self-auto"
>
Register Client
</Button>
<div className="w-full max-w-[var(--console-width)]">
<div className="mb-3 flex items-center gap-1.5 text-xs text-[var(--text-faint)]" aria-label="Breadcrumb">
<span>Console</span>
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
<span aria-current="page" className="text-[var(--text)]">Clients</span>
</div>
{/* Clients Table */}
<TableWrap>
<Table>
<TableHeader>
<TableRow>
<TableHead>Client ID</TableHead>
<TableHead>Client Name</TableHead>
<TableHead>Status</TableHead>
<TableHead>Rate Limit</TableHead>
<TableHead>Total Ingested</TableHead>
<TableHead>Created</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{clients.length === 0 ? (
<TableEmpty colSpan={7} message="No registered SDK clients yet." />
) : (
clients.map((client) => (
<TableRow key={client.clientId}>
<TableCell className="font-mono text-[11px] font-medium text-[var(--accent)]">
{client.clientId}
</TableCell>
<TableCell className="text-[11.5px] text-[var(--text)]">
{client.name}
</TableCell>
<TableCell>
<span
className={`text-[9.5px] font-mono px-1.5 py-0.5 border ${
client.status === 'active'
? 'border-[var(--success)] text-[var(--success)] bg-[var(--success-soft)]'
: 'border-[var(--danger)] text-[var(--danger)] bg-[var(--danger-soft)]'
}`}
>
{client.status.toUpperCase()}
</span>
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--text-muted)]">
{client.rateLimit} req/s
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--text)]">
{client.totalEvents.toLocaleString()}
</TableCell>
<TableCell className="text-[10.5px] text-[var(--text-dim)] font-mono">
{new Date(client.createdAt).toLocaleDateString()}
</TableCell>
<TableCell className="text-right">
<div className="flex items-center justify-end gap-1">
<Button
size="xs"
variant="secondary"
icon="Key"
onClick={() => {
setSelectedClient(client);
setTokenModalOpen(true);
}}
>
Token
</Button>
<Button
size="xs"
variant="ghost"
onClick={() => handleToggleStatus(client)}
>
{client.status === 'active' ? 'Revoke' : 'Activate'}
</Button>
<Button
size="xs"
variant="ghost"
icon="Trash2"
className="text-[var(--danger)]"
onClick={() => handleDeleteClient(client)}
/>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableWrap>
{/* Register Client Modal */}
<Modal
isOpen={createModalOpen}
onClose={() => setCreateModalOpen(false)}
title="Register Client SDK"
footer={
<>
<Button variant="ghost" size="sm" onClick={() => setCreateModalOpen(false)}>
Cancel
</Button>
<Button
variant="primary"
size="sm"
loading={submitting}
onClick={handleCreateClient}
>
Confirm
</Button>
</>
}
>
<form onSubmit={handleCreateClient} className="flex flex-col gap-3">
<Input
label="Client Identifier"
placeholder="e.g. py_order_service_04"
value={newClientId}
onChange={(e) => setNewClientId(e.target.value)}
required
/>
<Input
label="Client Name"
placeholder="e.g. Order Service"
value={newClientName}
onChange={(e) => setNewClientName(e.target.value)}
required
/>
<Input
label="Rate Limit (req/s)"
type="number"
min="1"
max="5000"
value={newRateLimit}
onChange={(e) => setNewRateLimit(e.target.value)}
/>
</form>
</Modal>
{/* View Token & Credentials Modal */}
<Modal
isOpen={tokenModalOpen}
onClose={() => setTokenModalOpen(false)}
title={`Credentials: ${selectedClient?.clientId}`}
footer={
<Button variant="secondary" size="sm" onClick={() => setTokenModalOpen(false)}>
Close
<AdminPageHeader
title="Clients"
subtitle="Registered SDK clients and their API access"
actions={
<Button type="button" variant="primary" size="sm" onClick={() => setModalOpen(true)}>
<Plus className="h-3.5 w-3.5" aria-hidden="true" />
New client
</Button>
}
>
{selectedClient && (
<div className="flex flex-col gap-3 font-mono text-[11px]">
<div>
<span className="text-[10px] text-[var(--text-dim)] uppercase tracking-wider block mb-1">
Client ID
</span>
<div className="p-2 bg-[var(--bg-main)] border border-[var(--border)] text-[var(--text)] flex items-center justify-between">
<span>{selectedClient.clientId}</span>
<Button
size="xs"
variant="ghost"
icon="Copy"
onClick={() => copyToClipboard(selectedClient.clientId, 'Client ID')}
/>
</div>
</div>
/>
<div>
<span className="text-[10px] text-[var(--text-dim)] uppercase tracking-wider block mb-1">
Client Secret Key
</span>
<div className="p-2 bg-[var(--bg-main)] border border-[var(--border)] text-[var(--text)] flex items-center justify-between">
<span className="truncate">{selectedClient.secret}</span>
<Button
size="xs"
variant="ghost"
icon="Copy"
onClick={() => copyToClipboard(selectedClient.secret, 'Client Secret')}
/>
</div>
</div>
<StatStrip
items={[
{ label: 'Total clients', value: clients.length },
{ label: 'Online now', value: onlineCount, dot: 'ok' },
{ label: 'Offline', value: offlineCount, dot: 'off' },
{ label: 'Pending setup', value: pendingCount, dot: 'pending' },
]}
/>
<div>
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-[var(--text-dim)] uppercase tracking-wider">
JWT Handshake Bearer Token
</span>
<Button
size="xs"
variant="ghost"
icon="RefreshCw"
onClick={() => handleRegenerateToken(selectedClient)}
>
Regenerate
</Button>
</div>
<textarea
readOnly
value={selectedClient.token}
rows={4}
className="w-full bg-[var(--bg-main)] border border-[var(--border)] p-2 text-[10.5px] text-[var(--accent)] resize-none"
/>
<Button
size="sm"
variant="secondary"
icon="Copy"
className="mt-1 w-full"
onClick={() => copyToClipboard(selectedClient.token, 'JWT Token')}
>
Copy JWT Token
</Button>
</div>
</div>
)}
</Modal>
<ClientsFilters
search={search}
onSearchChange={setSearch}
status={statusFilter}
onStatusChange={setStatusFilter}
counts={{ all: clients.length, online: onlineCount, offline: offlineCount, pending: pendingCount }}
/>
<ClientsTable clients={visibleClients} now={now} onStatusChange={fetchClients} />
<NewClientModal
open={modalOpen}
onClose={() => setModalOpen(false)}
onCreated={fetchClients}
/>
</div>
);
}
+2 -518
View File
@@ -1,521 +1,5 @@
'use client';
import React, { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Icon } from '@/components/ui/Icon';
import { Modal } from '@/components/ui/Modal';
import {
TableWrap,
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
interface EventItem {
eventId: string;
clientId: string;
timestamp: string;
payload: string;
}
const INITIAL_EVENTS: EventItem[] = [
{
eventId: 'evt_10482_a8',
clientId: 'py_telemetry_agent_01',
timestamp: '16:11:33',
payload: '{"action":"crawler_metric","pages_scraped":38,"latency_ms":24,"status":200}',
},
{
eventId: 'evt_10481_f2',
clientId: 'py_scraper_prod_02',
timestamp: '16:11:19',
payload: '{"spider":"market_catalog","items":114,"parse_time_s":1.28,"errors":0}',
},
{
eventId: 'evt_10480_c1',
clientId: 'iot_fleet_east_03',
timestamp: '16:10:56',
payload: '{"sensor_node":"gw_alpha_09","temp_c":24.3,"humidity_pct":58.1,"battery_v":3.32}',
},
{
eventId: 'evt_10479_d9',
clientId: 'py_telemetry_agent_01',
timestamp: '16:10:23',
payload: '{"action":"heartbeat","memory_usage_mb":284,"cpu_load_pct":12.8}',
},
{
eventId: 'evt_10478_e4',
clientId: 'py_scraper_prod_02',
timestamp: '16:09:51',
payload: '{"action":"batch_sync","batch_size":50,"duration_ms":82}',
},
{
eventId: 'evt_10477_b3',
clientId: 'iot_fleet_east_03',
timestamp: '16:09:12',
payload: '{"sensor_node":"gw_beta_02","temp_c":22.8,"humidity_pct":61.4,"battery_v":3.30}',
},
];
import { DashboardOverview } from '@/components/sections/DashboardOverview';
export default function DashboardPage() {
const { success, error, info } = useToast();
// Pre-seed realistic live state immediately to prevent empty voids on initial render
const [metrics, setMetrics] = useState<any>({
activeSockets: 3,
totalClients: 3,
activeClients: 3,
bufferStats: {
currentBufferSize: 18,
batchFlushThreshold: 500,
batchFlushIntervalMs: 2000,
totalIngested: 1438,
totalFlushed: 1420,
},
storageStats: {
totalMB: '0.74',
totalFiles: 3,
totalRows: 1420,
},
});
const [recentEvents, setRecentEvents] = useState<EventItem[]>(INITIAL_EVENTS);
const [storageFiles, setStorageFiles] = useState<any[]>([
{ filename: '2026-10-23.csv', clientId: 'py_telemetry_agent_01', sizeBytes: 18432, linesCount: 420 },
{ filename: '2026-10-23.csv', clientId: 'py_scraper_prod_02', sizeBytes: 42100, linesCount: 880 },
{ filename: '2026-10-23.csv', clientId: 'iot_fleet_east_03', sizeBytes: 12840, linesCount: 120 },
]);
const [simulating, setSimulating] = useState(false);
const [flushing, setFlushing] = useState(false);
const [inspectModalOpen, setInspectModalOpen] = useState(false);
const [inspectEvent, setInspectEvent] = useState<EventItem | null>(null);
// Sparkline rate values
const [throughputBars, setThroughputBars] = useState([
18, 24, 20, 38, 45, 32, 60, 52, 68, 58, 75, 70, 62, 54, 48, 64
]);
const fetchMetrics = useCallback(async () => {
try {
const res = await fetch('/api/metrics');
if (res.ok) {
const data = await res.json();
setMetrics(data);
}
const evtRes = await fetch('/api/events?limit=8');
if (evtRes.ok) {
const evtData = await evtRes.json();
if (evtData.events && evtData.events.length > 0) {
setRecentEvents(evtData.events);
}
}
const storRes = await fetch('/api/storage');
if (storRes.ok) {
const storData = await storRes.json();
if (storData.files && storData.files.length > 0) {
setStorageFiles(storData.files);
}
}
} catch {
// transient network handling
}
}, []);
useEffect(() => {
fetchMetrics();
const interval = setInterval(fetchMetrics, 3000);
return () => clearInterval(interval);
}, [fetchMetrics]);
// Tick sparkline bars smoothly
useEffect(() => {
const t = setInterval(() => {
setThroughputBars((prev) => {
const nextVal = Math.floor(Math.random() * 40) + 25;
return [...prev.slice(1), nextVal];
});
}, 2000);
return () => clearInterval(t);
}, []);
const handleQuickSimulate = async () => {
setSimulating(true);
try {
const res = await fetch('/api/events', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: 'py_telemetry_agent_01',
data: {
event: 'crawler_metric',
pages_scraped: Math.floor(Math.random() * 50) + 15,
latency_ms: Math.floor(Math.random() * 45) + 10,
status: 200,
},
}),
});
if (res.ok) {
const data = await res.json();
success('Telemetry Ingested', `Event ${data.event.eventId} buffered to Redis`);
fetchMetrics();
} else {
const errData = await res.json();
error('Simulation Failed', errData.error || 'Server error');
}
} catch (err: any) {
error('Network Error', err.message);
} finally {
setSimulating(false);
}
};
const handleManualFlush = async () => {
setFlushing(true);
try {
const res = await fetch('/api/storage', { method: 'POST' });
if (res.ok) {
const data = await res.json();
success('Buffer Flushed', `Appended ${data.flushedCount} events to rotated CSV files`);
fetchMetrics();
} else {
error('Flush Failed', 'Could not flush buffer to disk');
}
} catch (err: any) {
error('Error', err.message);
} finally {
setFlushing(false);
}
};
return (
<div className="flex flex-col gap-2.5">
{/* Top Action Bar */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[var(--border)] pb-2">
<div className="flex items-center gap-2">
<span className="w-2 h-2 bg-[var(--success)] inline-block" />
<h1 className="text-[14px] font-semibold text-[var(--text)] tracking-tight">
Telemetry Overview
</h1>
<span className="text-[9.5px] text-[var(--text-dim)] font-mono border border-[var(--border)] px-1.5 py-0.2 bg-[var(--bg-elevated)]">
LIVE INTAKE
</span>
</div>
<div className="flex items-center gap-1.5 self-start sm:self-auto">
<Button
size="xs"
variant="secondary"
icon="RotateCw"
onClick={fetchMetrics}
>
Refresh
</Button>
<Button
size="xs"
variant="secondary"
icon="HardDrive"
loading={flushing}
onClick={handleManualFlush}
>
Flush Buffer
</Button>
<Button
size="xs"
variant="primary"
icon="Play"
loading={simulating}
onClick={handleQuickSimulate}
>
Simulate Event
</Button>
</div>
</div>
{/* 4 Compact Metric Cards */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-1.5">
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<div className="flex items-center justify-between text-[8.5px] text-[var(--text-dim)] font-medium uppercase tracking-wider">
<span>Ingest Socket</span>
<Icon name="Radio" size={11} className="text-[var(--accent)]" />
</div>
<div className="flex items-baseline gap-1">
<span className="text-[15px] font-semibold text-[var(--text)] font-mono">:4000</span>
<span className="text-[9px] text-[var(--success)] font-mono">Online</span>
</div>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<div className="flex items-center justify-between text-[8.5px] text-[var(--text-dim)] font-medium uppercase tracking-wider">
<span>Buffer Queue</span>
<Icon name="Cpu" size={11} className="text-[var(--accent)]" />
</div>
<div className="flex items-baseline gap-1">
<span className="text-[15px] font-semibold text-[var(--text)] font-mono">
{metrics?.bufferStats?.currentBufferSize ?? 18}
</span>
<span className="text-[9px] text-[var(--text-dim)] font-mono">/ 500</span>
</div>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<div className="flex items-center justify-between text-[8.5px] text-[var(--text-dim)] font-medium uppercase tracking-wider">
<span>Total Flushed</span>
<Icon name="CheckCircle" size={11} className="text-[var(--success)]" />
</div>
<div className="flex items-baseline gap-1">
<span className="text-[15px] font-semibold text-[var(--text)] font-mono">
{(metrics?.bufferStats?.totalFlushed ?? 1420).toLocaleString()}
</span>
<span className="text-[9px] text-[var(--text-dim)] font-mono">rows</span>
</div>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<div className="flex items-center justify-between text-[8.5px] text-[var(--text-dim)] font-medium uppercase tracking-wider">
<span>Disk Storage</span>
<Icon name="HardDrive" size={11} className="text-[var(--accent)]" />
</div>
<div className="flex items-baseline gap-1">
<span className="text-[15px] font-semibold text-[var(--text)] font-mono">
{metrics?.storageStats?.totalMB ?? '0.74'}
</span>
<span className="text-[9px] text-[var(--text-dim)] font-mono">MB ({metrics?.storageStats?.totalFiles ?? 3} files)</span>
</div>
</Card>
</div>
{/* Main 2-Column Split Console Workbench (Zero Dead Space) */}
<div className="grid grid-cols-1 lg:grid-cols-12 gap-2">
{/* Left Column (8 cols): Throughput Sparkline & Live Stream Table */}
<div className="lg:col-span-8 flex flex-col gap-2">
{/* Realtime Throughput Activity Strip */}
<Card compact className="p-2 bg-[var(--bg-elevated)] flex flex-col gap-1">
<div className="flex items-center justify-between border-b border-[var(--border)] pb-1">
<div className="flex items-center gap-1.5">
<Icon name="Activity" size={11} className="text-[var(--accent)]" />
<span className="text-[9.5px] font-semibold uppercase tracking-wider text-[var(--text)]">
Throughput Rate (events / sec)
</span>
</div>
</div>
<div className="flex items-end gap-1 h-[42px] pt-1 px-1">
{throughputBars.map((val, idx) => (
<div key={idx} className="flex-1 flex flex-col items-center gap-0.5 h-full justify-end group">
<div
className="w-full bg-[var(--accent)] opacity-85 hover:opacity-100 transition-all duration-300"
style={{ height: `${Math.max(14, val)}%` }}
/>
<span className="text-[7px] font-mono text-[var(--text-dim)] hidden sm:block">
{val}
</span>
</div>
))}
</div>
</Card>
{/* Recent Buffered Ingestion Events */}
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5">
<Icon name="List" size={11} className="text-[var(--accent)]" />
<h2 className="text-[11.5px] font-semibold text-[var(--text)]">
Live Buffer Stream
</h2>
</div>
<Link href="/vcon/data">
<Button size="xs" variant="ghost" icon="ArrowRight" iconPosition="right">
Full Stream
</Button>
</Link>
</div>
<TableWrap>
<Table>
<TableHeader>
<TableRow>
<TableHead>Event ID</TableHead>
<TableHead>Client ID</TableHead>
<TableHead>Time</TableHead>
<TableHead>Payload Preview</TableHead>
<TableHead className="text-right">Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{recentEvents.map((evt, idx) => (
<TableRow key={idx}>
<TableCell className="font-mono text-[9.5px] text-[var(--text)]">
{evt.eventId}
</TableCell>
<TableCell className="font-mono text-[9.5px] text-[var(--accent)]">
{evt.clientId}
</TableCell>
<TableCell className="font-mono text-[9px]">
{evt.timestamp ? (evt.timestamp.includes('T') ? new Date(evt.timestamp).toLocaleTimeString() : evt.timestamp) : 'now'}
</TableCell>
<TableCell className="font-mono text-[9px] text-[var(--text-muted)] max-w-[200px] sm:max-w-[260px] truncate">
{evt.payload}
</TableCell>
<TableCell className="text-right">
<Button
size="xs"
variant="ghost"
icon="Maximize2"
onClick={() => {
setInspectEvent(evt);
setInspectModalOpen(true);
}}
>
View
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableWrap>
</div>
</div>
{/* Right Column (4 cols): Runtime Health, Client SDKs, Disk Partitions */}
<div className="lg:col-span-4 flex flex-col gap-2">
{/* Process Allocation & Health Card */}
<Card compact className="p-2 bg-[var(--bg-elevated)] flex flex-col gap-1">
<div className="flex items-center justify-between border-b border-[var(--border)] pb-1">
<span className="text-[9.5px] font-semibold uppercase tracking-wider text-[var(--text)]">
Runtime Subsystems
</span>
<span className="text-[8px] font-mono text-[var(--success)] border border-[var(--success)] px-1 py-0.2">
Healthy
</span>
</div>
<div className="flex flex-col gap-0.5 text-[9.5px] font-mono">
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-medium text-[var(--text)]">Express Socket.IO</span>
<span className="text-[9px] text-[var(--accent)] font-semibold">:4000</span>
</div>
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-medium text-[var(--text)]">Next.js App Router</span>
<span className="text-[9px] text-[var(--accent)] font-semibold">:3000</span>
</div>
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-medium text-[var(--text)]">CSV Disk Worker</span>
<span className="text-[9px] text-[var(--success)] font-semibold">Active</span>
</div>
</div>
</Card>
{/* Active SDK Clients Mini Table */}
<Card compact className="p-2 bg-[var(--bg-elevated)] flex flex-col gap-1">
<div className="flex items-center justify-between border-b border-[var(--border)] pb-1">
<span className="text-[9.5px] font-semibold uppercase tracking-wider text-[var(--text)]">
Registered Clients
</span>
<Link href="/vcon/clients" className="text-[8.5px] text-[var(--accent)] hover:underline">
Manage
</Link>
</div>
<div className="flex flex-col gap-0.5 text-[9.5px]">
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-mono text-[var(--text)] text-[9px] truncate">
py_telemetry_agent_01
</span>
<span className="text-[8px] font-mono text-[var(--success)] shrink-0">150 req/s</span>
</div>
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-mono text-[var(--text)] text-[9px] truncate">
py_scraper_prod_02
</span>
<span className="text-[8px] font-mono text-[var(--success)] shrink-0">200 req/s</span>
</div>
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-mono text-[var(--text)] text-[9px] truncate">
iot_fleet_east_03
</span>
<span className="text-[8px] font-mono text-[var(--success)] shrink-0">50 req/s</span>
</div>
</div>
</Card>
{/* Quick Storage Partitions Preview */}
<Card compact className="p-2 bg-[var(--bg-elevated)] flex flex-col gap-1">
<div className="flex items-center justify-between border-b border-[var(--border)] pb-1">
<span className="text-[9.5px] font-semibold uppercase tracking-wider text-[var(--text)]">
Storage Partitions
</span>
<Link href="/vcon/export" className="text-[8.5px] text-[var(--accent)] hover:underline">
Export CSV
</Link>
</div>
<div className="flex flex-col gap-0.5 text-[9px] font-mono">
{storageFiles.slice(0, 3).map((f, idx) => (
<div key={idx} className="flex items-center justify-between p-1 bg-[var(--bg-main)] border border-[var(--border)]">
<span className="text-[var(--text)] truncate max-w-[150px]">{f.clientId}/{f.filename}</span>
<span className="text-[var(--text-dim)]">{(f.sizeBytes / 1024).toFixed(1)} KB</span>
</div>
))}
</div>
</Card>
</div>
</div>
{/* Inspect Event Modal */}
<Modal
isOpen={inspectModalOpen}
onClose={() => setInspectModalOpen(false)}
title={`Event: ${inspectEvent?.eventId}`}
description={`Origin Client: ${inspectEvent?.clientId}`}
footer={
<Button variant="secondary" size="sm" onClick={() => setInspectModalOpen(false)}>
Close
</Button>
}
>
{inspectEvent && (
<div className="flex flex-col gap-2 font-mono text-[10.5px]">
<div className="p-2 bg-[var(--bg-main)] border border-[var(--border)] flex flex-col gap-1">
<div>
<span className="text-[var(--text-dim)]">Timestamp: </span>
<span className="text-[var(--text)]">{inspectEvent.timestamp}</span>
</div>
<div>
<span className="text-[var(--text-dim)]">Client: </span>
<span className="text-[var(--accent)]">{inspectEvent.clientId}</span>
</div>
</div>
<div>
<span className="text-[9.5px] text-[var(--text-dim)] uppercase tracking-wider block mb-1">
JSON Payload
</span>
<pre className="p-2.5 bg-[var(--bg-main)] border border-[var(--border)] text-[var(--text)] overflow-x-auto max-h-[220px]">
{(() => {
try {
return JSON.stringify(JSON.parse(inspectEvent.payload), null, 2);
} catch {
return inspectEvent.payload;
}
})()}
</pre>
</div>
</div>
)}
</Modal>
</div>
);
return <DashboardOverview />;
}
+3 -284
View File
@@ -1,286 +1,5 @@
'use client';
import { DataBrowser } from '@/components/sections';
import React, { useState, useEffect, useCallback } from 'react';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Input, Select } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import { Icon } from '@/components/ui/Icon';
import {
TableWrap,
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
TableEmpty,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
interface StreamEvent {
clientId: string;
eventId: string;
timestamp: string;
payload: string;
}
export default function LiveDataPage() {
const { success, error } = useToast();
const [events, setEvents] = useState<StreamEvent[]>([]);
const [clients, setClients] = useState<{ clientId: string; name: string }[]>([]);
const [selectedClient, setSelectedClient] = useState<string>('all');
const [searchQuery, setSearchQuery] = useState<string>('');
const [isPaused, setIsPaused] = useState<boolean>(false);
const [selectedEvent, setSelectedEvent] = useState<StreamEvent | null>(null);
const [modalOpen, setModalOpen] = useState(false);
const fetchClients = useCallback(async () => {
try {
const res = await fetch('/api/clients');
if (res.ok) {
const data = await res.json();
setClients(data.clients || []);
}
} catch {
// ignore
}
}, []);
const fetchEvents = useCallback(async () => {
if (isPaused) return;
try {
const url = selectedClient !== 'all'
? `/api/events?clientId=${encodeURIComponent(selectedClient)}&limit=100`
: '/api/events?limit=100';
const res = await fetch(url);
if (res.ok) {
const data = await res.json();
setEvents(data.events || []);
}
} catch {
// ignore
}
}, [isPaused, selectedClient]);
useEffect(() => {
fetchClients();
}, [fetchClients]);
useEffect(() => {
fetchEvents();
const interval = setInterval(fetchEvents, 2000);
return () => clearInterval(interval);
}, [fetchEvents]);
const handleSimulate = async () => {
try {
const targetClientId = selectedClient !== 'all' ? selectedClient : 'py_telemetry_agent_01';
const res = await fetch('/api/events', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: targetClientId,
data: {
source: 'live_stream_simulator',
reading: +(Math.random() * 100).toFixed(2),
status: 'OK',
timestamp_ms: Date.now(),
},
}),
});
if (res.ok) {
const data = await res.json();
success('Stream Event Emitted', `Event ${data.event.eventId} pushed`);
fetchEvents();
}
} catch (err: any) {
error('Failed to emit', err.message);
}
};
const filteredEvents = events.filter((e) => {
if (!searchQuery) return true;
const q = searchQuery.toLowerCase();
return (
e.eventId.toLowerCase().includes(q) ||
e.clientId.toLowerCase().includes(q) ||
e.payload.toLowerCase().includes(q)
);
});
return (
<div className="flex flex-col gap-4">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[var(--border)] pb-2">
<h1 className="text-[14px] font-semibold text-[var(--text)] tracking-tight">
Live Stream
</h1>
<div className="flex items-center gap-1.5 self-start sm:self-auto">
<Button
size="xs"
variant={isPaused ? 'primary' : 'secondary'}
icon={isPaused ? 'Play' : 'Pause'}
onClick={() => setIsPaused((prev) => !prev)}
>
{isPaused ? 'Resume' : 'Pause'}
</Button>
<Button
size="xs"
variant="secondary"
icon="Radio"
onClick={handleSimulate}
>
Emit Event
</Button>
</div>
</div>
{/* Filter Toolbar */}
<Card compact className="p-2.5 bg-[var(--bg-elevated)] flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-2.5 flex-1 min-w-[240px]">
<div className="w-[180px]">
<Select
value={selectedClient}
onChange={(e) => setSelectedClient(e.target.value)}
>
<option value="all">All Clients</option>
{clients.map((c) => (
<option key={c.clientId} value={c.clientId}>
{c.clientId}
</option>
))}
</Select>
</div>
<div className="flex-1 min-w-[160px] max-w-[340px]">
<Input
placeholder="Search eventId or payload content..."
icon="Search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
</div>
<div className="flex items-center gap-2 text-[11px] font-mono text-[var(--text-dim)]">
<span className="flex items-center gap-1.5">
<span
className={`w-2 h-2 inline-block ${
isPaused ? 'bg-[var(--warning)]' : 'bg-[var(--success)] animate-pulse'
}`}
/>
<span>{isPaused ? 'PAUSED' : 'STREAMING'}</span>
</span>
<span>|</span>
<span>{filteredEvents.length} events</span>
</div>
</Card>
{/* Events Table */}
<TableWrap>
<Table>
<TableHeader>
<TableRow>
<TableHead>Event ID</TableHead>
<TableHead>Client ID</TableHead>
<TableHead>Ingestion Timestamp</TableHead>
<TableHead>Payload Preview</TableHead>
<TableHead className="text-right">Inspect</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredEvents.length === 0 ? (
<TableEmpty
colSpan={5}
message={
isPaused
? 'Stream is paused.'
: 'No incoming events in memory buffer yet. Click "Emit Event" above or sync via Python SDK.'
}
/>
) : (
filteredEvents.map((evt, idx) => (
<TableRow key={idx}>
<TableCell className="font-mono text-[11px] text-[var(--text)]">
{evt.eventId}
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--accent)]">
{evt.clientId}
</TableCell>
<TableCell className="font-mono text-[10.5px]">
{evt.timestamp}
</TableCell>
<TableCell className="font-mono text-[10.5px] text-[var(--text-muted)] max-w-[300px] truncate">
{evt.payload}
</TableCell>
<TableCell className="text-right">
<Button
size="xs"
variant="ghost"
icon="Maximize2"
onClick={() => {
setSelectedEvent(evt);
setModalOpen(true);
}}
>
Inspect
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableWrap>
{/* Inspect Event Modal */}
<Modal
isOpen={modalOpen}
onClose={() => setModalOpen(false)}
title={`Event Inspector: ${selectedEvent?.eventId}`}
description={`Origin Client: ${selectedEvent?.clientId}`}
footer={
<Button variant="secondary" size="sm" onClick={() => setModalOpen(false)}>
Close
</Button>
}
>
{selectedEvent && (
<div className="flex flex-col gap-3 font-mono text-[11px]">
<div className="grid grid-cols-2 gap-2 text-[10.5px] p-2 bg-[var(--bg-main)] border border-[var(--border)]">
<div>
<span className="text-[var(--text-dim)]">Event ID: </span>
<span className="text-[var(--text)] font-semibold">{selectedEvent.eventId}</span>
</div>
<div>
<span className="text-[var(--text-dim)]">Client: </span>
<span className="text-[var(--accent)] font-semibold">{selectedEvent.clientId}</span>
</div>
<div className="col-span-2">
<span className="text-[var(--text-dim)]">Timestamp: </span>
<span className="text-[var(--text)]">{selectedEvent.timestamp}</span>
</div>
</div>
<div>
<span className="text-[10px] text-[var(--text-dim)] uppercase tracking-wider block mb-1">
JSON Payload Structure
</span>
<pre className="p-3 bg-[var(--bg-main)] border border-[var(--border)] text-[var(--text)] text-[11px] overflow-x-auto max-h-[300px]">
{(() => {
try {
return JSON.stringify(JSON.parse(selectedEvent.payload), null, 2);
} catch {
return selectedEvent.payload;
}
})()}
</pre>
</div>
</div>
)}
</Modal>
</div>
);
export default function DataPage() {
return <DataBrowser />;
}
+2 -193
View File
@@ -1,196 +1,5 @@
'use client';
import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Select } from '@/components/ui/Input';
import { Icon } from '@/components/ui/Icon';
import {
TableWrap,
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
TableEmpty,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
import { ExportWorkspace } from '@/components/sections/ExportWorkspace';
export default function ExportPage() {
const { success, info } = useToast();
const [clients, setClients] = useState<{ clientId: string; name: string }[]>([]);
const [selectedClient, setSelectedClient] = useState<string>('all');
const [files, setFiles] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const fetchData = useCallback(async () => {
try {
const clientRes = await fetch('/api/clients');
if (clientRes.ok) {
const clientData = await clientRes.json();
setClients(clientData.clients || []);
}
const storageRes = await fetch(`/api/storage?clientId=${encodeURIComponent(selectedClient)}`);
if (storageRes.ok) {
const storageData = await storageRes.json();
setFiles(storageData.files || []);
}
} catch {
// ignore
} finally {
setLoading(false);
}
}, [selectedClient]);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleExportAll = () => {
const url = `/api/export?clientId=${encodeURIComponent(selectedClient)}`;
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `${selectedClient}_export.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
info('Export Initiated', `Streaming CSV download for client ${selectedClient}`);
};
const handleDownloadFile = (clientId: string, filename: string) => {
const url = `/api/export?clientId=${encodeURIComponent(clientId)}&filename=${encodeURIComponent(filename)}`;
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
success('File Download Started', filename);
};
return (
<div className="flex flex-col gap-4">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[var(--border)] pb-2">
<h1 className="text-[14px] font-semibold text-[var(--text)] tracking-tight">
CSV Exporter
</h1>
<Button
size="xs"
variant="primary"
icon="Download"
onClick={handleExportAll}
className="self-start sm:self-auto"
>
Download All CSV
</Button>
</div>
{/* Filter and Endpoint Specs */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-2">
<Card compact className="flex flex-col gap-1.5 p-2 bg-[var(--bg-elevated)]">
<CardHeader className="p-0 pb-1 mb-0 border-b-0">
<CardTitle className="text-[11px]">Filter Scope</CardTitle>
</CardHeader>
<CardContent className="p-0 flex flex-col gap-1.5">
<Select
value={selectedClient}
onChange={(e) => setSelectedClient(e.target.value)}
>
<option value="all">All Clients</option>
{clients.map((c) => (
<option key={c.clientId} value={c.clientId}>
{c.clientId}
</option>
))}
</Select>
<div className="text-[9.5px] text-[var(--text-dim)] font-mono">
Files: {files.length}
</div>
</CardContent>
</Card>
<Card compact className="md:col-span-2 flex flex-col gap-1 p-2 bg-[var(--bg-elevated)] font-mono text-[10px]">
<CardHeader className="p-0 pb-1 mb-0 border-b-0">
<CardTitle className="text-[11px]">API Export Endpoint</CardTitle>
</CardHeader>
<CardContent className="p-0 flex flex-col gap-1">
<div className="p-1.5 bg-[var(--bg-main)] border border-[var(--border)] flex items-center justify-between">
<span className="text-[var(--accent)]">GET /api/export?clientId={selectedClient}</span>
<span className="text-[9px] text-[var(--text-dim)]">Stream</span>
</div>
</CardContent>
</Card>
</div>
{/* Partitioned Files List */}
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<h2 className="text-[13px] font-semibold text-[var(--text)]">
Stored CSV Partitions
</h2>
<span className="text-[10.5px] text-[var(--text-dim)] font-mono">
/storage/data/&#123;clientId&#125;/&#123;YYYY-MM-DD&#125;.csv
</span>
</div>
<TableWrap>
<Table>
<TableHeader>
<TableRow>
<TableHead>File Name</TableHead>
<TableHead>Client ID</TableHead>
<TableHead>Date Partition</TableHead>
<TableHead>Approx. Rows</TableHead>
<TableHead>Size (KB)</TableHead>
<TableHead>Last Modified</TableHead>
<TableHead className="text-right">Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{files.length === 0 ? (
<TableEmpty colSpan={7} message="No CSV partitions found for selected client." />
) : (
files.map((file, idx) => (
<TableRow key={idx}>
<TableCell className="font-mono text-[11px] font-medium text-[var(--text)]">
{file.filename}
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--accent)]">
{file.clientId}
</TableCell>
<TableCell className="font-mono text-[11px]">
{file.date}
</TableCell>
<TableCell className="font-mono text-[11px]">
{file.linesCount.toLocaleString()}
</TableCell>
<TableCell className="font-mono text-[11px]">
{(file.sizeBytes / 1024).toFixed(1)} KB
</TableCell>
<TableCell className="text-[10.5px] text-[var(--text-dim)] font-mono">
{new Date(file.modifiedAt).toLocaleString()}
</TableCell>
<TableCell className="text-right">
<Button
size="xs"
variant="secondary"
icon="Download"
onClick={() => handleDownloadFile(file.clientId, file.filename)}
>
Download
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableWrap>
</div>
</div>
);
return <ExportWorkspace />;
}
+5 -1
View File
@@ -1,8 +1,12 @@
'use client';
import React from 'react';
import { MainLayout } from '@/components/layout/MainLayout';
import { usePathname } from 'next/navigation';
import React from 'react';
export default function VconLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
if (pathname === '/vcon/login') return <>{children}</>;
return <MainLayout showSidebar={true}>{children}</MainLayout>;
}
+5
View File
@@ -0,0 +1,5 @@
import { AdminLogin } from '@/components/sections/AdminLogin';
export default function LoginPage() {
return <AdminLogin />;
}
+7 -8
View File
@@ -1,11 +1,10 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card';
import { Select } from '@/components/ui/Input';
import { Icon } from '@/components/ui/Icon';
import { useToast } from '@/components/ui/Toast';
import { useEffect, useState } from 'react';
export default function SdkGuidePage() {
const { success } = useToast();
@@ -73,7 +72,7 @@ if client.connect():
<div className="flex flex-col gap-4 max-w-[960px]">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[var(--border)] pb-2">
<h1 className="text-[14px] font-semibold text-[var(--text)] tracking-tight">
<h1 className="text-[22px] font-semibold text-[var(--text)]">
Python SDK
</h1>
@@ -89,8 +88,8 @@ if client.connect():
</div>
{/* Installation Step */}
<Card compact className="flex flex-col gap-1.5 font-mono text-[10.5px]">
<div className="p-2 bg-[var(--bg-main)] border border-[var(--border)] flex items-center justify-between">
<Card compact className="flex flex-col gap-3 font-mono text-[13px]">
<div className="p-3 bg-[var(--bg-main)] border border-[var(--border)] flex items-center justify-between">
<span className="text-[var(--accent)]">pip install ./sdk-python</span>
<Button
size="xs"
@@ -105,7 +104,7 @@ if client.connect():
<Card compact className="flex flex-col gap-2">
<CardHeader className="p-0 pb-1 mb-0 border-b-0">
<div className="flex flex-wrap items-center justify-between gap-2 w-full">
<CardTitle className="text-[11.5px]">Client Code Example</CardTitle>
<CardTitle>Client Code Example</CardTitle>
{clients.length > 0 && (
<div className="w-[180px]">
<Select
@@ -126,7 +125,7 @@ if client.connect():
<CardContent className="p-0 flex flex-col gap-1">
<div className="relative">
<pre className="p-2.5 bg-[var(--bg-main)] border border-[var(--border)] text-[var(--text)] text-[10.5px] font-mono overflow-x-auto leading-relaxed">
<pre className="p-4 bg-[var(--bg-main)] border border-[var(--border)] text-[var(--text)] text-[12px] font-mono overflow-x-auto leading-relaxed">
{pythonSnippet}
</pre>
</div>
+2 -207
View File
@@ -1,210 +1,5 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Form, FormRow, FormSwitch } from '@/components/ui/Form';
import { Icon } from '@/components/ui/Icon';
import { useToast } from '@/components/ui/Toast';
import { SettingsWorkspace } from '@/components/sections/SettingsWorkspace';
export default function SettingsPage() {
const { success, error } = useToast();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// Settings State
const [maxEventsPerSec, setMaxEventsPerSec] = useState('100');
const [maxPayloadSizeKb, setMaxPayloadSizeKb] = useState('100');
const [batchFlushThreshold, setBatchFlushThreshold] = useState('500');
const [batchFlushIntervalMs, setBatchFlushIntervalMs] = useState('2000');
const [fileRotationMb, setFileRotationMb] = useState('100');
const [jwtSecret, setJwtSecret] = useState('datastack-universal-secret-key-2026');
const [enableIdempotency, setEnableIdempotency] = useState(true);
const [autoPruneDays, setAutoPruneDays] = useState('30');
useEffect(() => {
async function loadSettings() {
try {
const res = await fetch('/api/settings');
if (res.ok) {
const data = await res.json();
const s = data.settings;
setMaxEventsPerSec(String(s.maxEventsPerSec ?? 100));
setMaxPayloadSizeKb(String(s.maxPayloadSizeKb ?? 100));
setBatchFlushThreshold(String(s.batchFlushThreshold ?? 500));
setBatchFlushIntervalMs(String(s.batchFlushIntervalMs ?? 2000));
setFileRotationMb(String(s.fileRotationMb ?? 100));
setJwtSecret(s.jwtSecret ?? 'datastack-universal-secret-key-2026');
setEnableIdempotency(Boolean(s.enableIdempotency ?? true));
setAutoPruneDays(String(s.autoPruneDays ?? 30));
}
} catch {
// ignore
} finally {
setLoading(false);
}
}
loadSettings();
}, []);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
try {
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
maxEventsPerSec: Number(maxEventsPerSec),
maxPayloadSizeKb: Number(maxPayloadSizeKb),
batchFlushThreshold: Number(batchFlushThreshold),
batchFlushIntervalMs: Number(batchFlushIntervalMs),
fileRotationMb: Number(fileRotationMb),
jwtSecret,
enableIdempotency,
autoPruneDays: Number(autoPruneDays),
}),
});
if (res.ok) {
success('Settings Saved', 'Core engine configuration updated and propagated');
} else {
error('Save Failed', 'Server rejected configuration payload');
}
} catch (err: any) {
error('Error', err.message);
} finally {
setSaving(false);
}
};
return (
<div className="flex flex-col gap-4 max-w-[900px]">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[var(--border)] pb-2">
<h1 className="text-[14px] font-semibold text-[var(--text)] tracking-tight">
Settings
</h1>
<Button
size="xs"
variant="primary"
icon="Save"
loading={saving}
onClick={handleSave}
className="self-start sm:self-auto"
>
Save
</Button>
</div>
<Form onSubmit={handleSave}>
{/* Ingestion & Rate Limit Group */}
<Card compact className="flex flex-col gap-3">
<CardHeader className="p-0 pb-1.5 mb-1.5">
<div className="flex items-center gap-2">
<Icon name="Activity" size={14} className="text-[var(--accent)]" />
<CardTitle>Throughput & Safety Limits</CardTitle>
</div>
</CardHeader>
<CardContent className="p-0 flex flex-col gap-3">
<FormRow>
<Input
label="Global Max Events / Second (Rate Limit)"
type="number"
min="10"
max="10000"
value={maxEventsPerSec}
onChange={(e) => setMaxEventsPerSec(e.target.value)}
/>
<Input
label="Max Payload Size per Event (KB)"
type="number"
min="1"
max="5120"
value={maxPayloadSizeKb}
onChange={(e) => setMaxPayloadSizeKb(e.target.value)}
/>
</FormRow>
<FormSwitch
label="Enable Idempotency Key Deduplication"
description="clientId + eventId combinations are rejected within 5-minute TTL window"
checked={enableIdempotency}
onChange={setEnableIdempotency}
/>
</CardContent>
</Card>
{/* Buffer & CSV Rotation Group */}
<Card compact className="flex flex-col gap-3">
<CardHeader className="p-0 pb-1.5 mb-1.5">
<div className="flex items-center gap-2">
<Icon name="HardDrive" size={14} className="text-[var(--accent)]" />
<CardTitle>Redis In-Memory Buffer & CSV Partitioning</CardTitle>
</div>
</CardHeader>
<CardContent className="p-0 flex flex-col gap-3">
<FormRow>
<Input
label="Batch Flush Threshold (Row Count)"
type="number"
min="50"
max="5000"
value={batchFlushThreshold}
onChange={(e) => setBatchFlushThreshold(e.target.value)}
/>
<Input
label="Batch Flush Timer Interval (Milliseconds)"
type="number"
min="500"
max="10000"
value={batchFlushIntervalMs}
onChange={(e) => setBatchFlushIntervalMs(e.target.value)}
/>
</FormRow>
<FormRow>
<Input
label="File Rotation Threshold (MB)"
type="number"
min="10"
max="1000"
value={fileRotationMb}
onChange={(e) => setFileRotationMb(e.target.value)}
/>
<Input
label="Log Archive Retention (Days)"
type="number"
min="1"
max="365"
value={autoPruneDays}
onChange={(e) => setAutoPruneDays(e.target.value)}
/>
</FormRow>
</CardContent>
</Card>
{/* Security & Token Group */}
<Card compact className="flex flex-col gap-3">
<CardHeader className="p-0 pb-1.5 mb-1.5">
<div className="flex items-center gap-2">
<Icon name="Key" size={14} className="text-[var(--accent)]" />
<CardTitle>Authentication Secret</CardTitle>
</div>
</CardHeader>
<CardContent className="p-0 flex flex-col gap-3">
<Input
label="JWT Signature Secret Key"
type="password"
value={jwtSecret}
onChange={(e) => setJwtSecret(e.target.value)}
/>
<div className="text-[10.5px] text-[var(--text-dim)] font-mono">
Note: Updating this secret invalidates existing client handshake tokens immediately.
</div>
</CardContent>
</Card>
</Form>
</div>
);
return <SettingsWorkspace />;
}
+8 -9
View File
@@ -1,11 +1,10 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card';
import { Select, Textarea } from '@/components/ui/Input';
import { Icon } from '@/components/ui/Icon';
import { useToast } from '@/components/ui/Toast';
import { useEffect, useState } from 'react';
export default function SimulatorPage() {
const { success, error } = useToast();
@@ -112,7 +111,7 @@ export default function SimulatorPage() {
<div className="flex flex-col gap-4 max-w-[960px]">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[var(--border)] pb-2">
<h1 className="text-[14px] font-semibold text-[var(--text)] tracking-tight">
<h1 className="text-[22px] font-semibold text-[var(--text)]">
Simulator
</h1>
@@ -137,11 +136,11 @@ export default function SimulatorPage() {
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-2">
<div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
{/* Editor Card */}
<Card compact className="flex flex-col gap-2 p-2 bg-[var(--bg-elevated)]">
<CardHeader className="p-0 pb-1 mb-0 border-b-0">
<CardTitle className="text-[11px]">Payload Configuration</CardTitle>
<CardTitle>Payload Configuration</CardTitle>
</CardHeader>
<CardContent className="p-0 flex flex-col gap-2">
<Select
@@ -164,13 +163,13 @@ export default function SimulatorPage() {
</Card>
{/* Response Inspector */}
<Card compact className="flex flex-col gap-1.5 p-2 bg-[var(--bg-elevated)] font-mono text-[10px]">
<Card compact className="flex flex-col gap-3 bg-[var(--bg-elevated)] font-mono text-[12px]">
<CardHeader className="p-0 pb-1 mb-0 border-b-0">
<CardTitle className="text-[11px]">Pipeline Response</CardTitle>
<CardTitle>Pipeline Response</CardTitle>
</CardHeader>
<CardContent className="p-0 flex flex-col gap-1">
{lastResponse ? (
<pre className="p-2.5 bg-[var(--bg-main)] border border-[var(--border)] text-[var(--text)] overflow-x-auto max-h-[240px]">
<pre className="p-4 bg-[var(--bg-main)] border border-[var(--border)] text-[12px] text-[var(--text)] overflow-x-auto max-h-[320px]">
{JSON.stringify(lastResponse, null, 2)}
</pre>
) : (
+26 -27
View File
@@ -1,20 +1,19 @@
'use client';
import React, { useState, useEffect, useCallback } from 'react';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Icon } from '@/components/ui/Icon';
import { Card } from '@/components/ui/Card';
import {
TableWrap,
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
TableEmpty,
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
import { useCallback, useEffect, useState } from 'react';
export default function StoragePage() {
const { success, error } = useToast();
@@ -64,7 +63,7 @@ export default function StoragePage() {
<div className="flex flex-col gap-4">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[var(--border)] pb-2">
<h1 className="text-[14px] font-semibold text-[var(--text)] tracking-tight">
<h1 className="text-[22px] font-semibold text-[var(--text)]">
CSV Storage
</h1>
@@ -90,31 +89,31 @@ export default function StoragePage() {
</div>
{/* Storage Summary Cards */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-1.5">
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-3">
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<span className="text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">Disk Usage</span>
<span className="text-[15px] font-semibold text-[var(--text)] font-mono">
<span className="text-[12px] uppercase text-[var(--text-muted)] font-medium">Disk Usage</span>
<span className="text-[22px] font-semibold text-[var(--text)] font-mono">
{stats?.totalMB ?? '0.00'} MB
</span>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<span className="text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">CSV Files</span>
<span className="text-[15px] font-semibold text-[var(--text)] font-mono">
<span className="text-[12px] uppercase text-[var(--text-muted)] font-medium">CSV Files</span>
<span className="text-[22px] font-semibold text-[var(--text)] font-mono">
{stats?.totalFiles ?? 0}
</span>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<span className="text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">Persisted Rows</span>
<span className="text-[15px] font-semibold text-[var(--text)] font-mono">
<span className="text-[12px] uppercase text-[var(--text-muted)] font-medium">Persisted Rows</span>
<span className="text-[22px] font-semibold text-[var(--text)] font-mono">
{stats?.totalRows ? stats.totalRows.toLocaleString() : 0}
</span>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<span className="text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">Rotation Rule</span>
<span className="text-[13px] font-semibold text-[var(--accent)] font-mono">
<span className="text-[12px] uppercase text-[var(--text-muted)] font-medium">Rotation Rule</span>
<span className="text-[17px] font-semibold text-[var(--accent)] font-mono">
100MB / Daily
</span>
</Card>
@@ -122,7 +121,7 @@ export default function StoragePage() {
{/* Partition Files Table */}
<div className="flex flex-col gap-2">
<h2 className="text-[13px] font-semibold text-[var(--text)]">
<h2 className="text-[17px] font-semibold text-[var(--text)]">
CSV Files on Disk
</h2>
@@ -143,19 +142,19 @@ export default function StoragePage() {
) : (
files.map((file, idx) => (
<TableRow key={idx}>
<TableCell className="font-mono text-[11px] text-[var(--accent)]">
<TableCell className="font-mono text-[12px] text-[var(--accent)]">
{file.clientId}
</TableCell>
<TableCell className="font-mono text-[11px] font-medium text-[var(--text)]">
<TableCell className="font-mono text-[12px] font-medium text-[var(--text)]">
{file.filename}
</TableCell>
<TableCell className="font-mono text-[11px]">
<TableCell className="font-mono text-[12px]">
{(file.sizeBytes / 1024).toFixed(1)} KB
</TableCell>
<TableCell className="font-mono text-[11px]">
<TableCell className="font-mono text-[12px]">
{file.linesCount.toLocaleString()}
</TableCell>
<TableCell className="text-[10.5px] text-[var(--text-dim)] font-mono">
<TableCell className="text-[12px] text-[var(--text-dim)] font-mono">
{new Date(file.modifiedAt).toLocaleString()}
</TableCell>
</TableRow>