refactor(auth): standardize session management and security
- Centralize secret retrieval using `getAdminSessionSecret` - Replace manual session parsing with `verifyRequestAdminSession` utility - Tighten API validation and improve security headers handling - Enforce environment variable security for production deployments
This commit is contained in:
1 parent
34519c07df
commit
177ed4a844
78 files changed
+6748
-3157
No files matched your search
@@ -23,7 +23,11 @@ export default function ClientsPage() {
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
const fetchClients = useCallback(async () => {
|
||||
const response = await fetch('/api/clients');
|
||||
const response = await fetch('/api/clients', { cache: 'no-store' });
|
||||
if (response.status === 401) {
|
||||
window.location.assign('/vcon/login');
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error('Unable to load clients');
|
||||
const data = await response.json();
|
||||
setClients(setCached('vcon:clients', data.clients || []));
|
||||
@@ -49,16 +53,19 @@ export default function ClientsPage() {
|
||||
!query ||
|
||||
client.clientId.toLowerCase().includes(query) ||
|
||||
client.name.toLowerCase().includes(query);
|
||||
const revoked = client.status === 'revoked';
|
||||
const online =
|
||||
client.status === 'active' &&
|
||||
Boolean(client.lastActive) &&
|
||||
now - new Date(client.lastActive!).getTime() < 60_000;
|
||||
const pending = client.status === 'active' && !client.lastActive;
|
||||
const offline = client.status === 'active' && !online && !pending;
|
||||
const matchesStatus =
|
||||
statusFilter === 'all' ||
|
||||
(statusFilter === 'online' && online) ||
|
||||
(statusFilter === 'offline' && !online && !pending) ||
|
||||
(statusFilter === 'pending' && pending);
|
||||
(statusFilter === 'offline' && offline) ||
|
||||
(statusFilter === 'pending' && pending) ||
|
||||
(statusFilter === 'revoked' && revoked);
|
||||
return matchesSearch && matchesStatus;
|
||||
});
|
||||
}, [clients, now, search, statusFilter]);
|
||||
@@ -72,7 +79,10 @@ export default function ClientsPage() {
|
||||
const pendingCount = clients.filter(
|
||||
(client) => client.status === 'active' && !client.lastActive
|
||||
).length;
|
||||
const offlineCount = clients.length - onlineCount - pendingCount;
|
||||
const revokedCount = clients.filter(
|
||||
(client) => client.status === 'revoked'
|
||||
).length;
|
||||
const offlineCount = clients.length - onlineCount - pendingCount - revokedCount;
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
@@ -90,11 +100,13 @@ export default function ClientsPage() {
|
||||
}
|
||||
>
|
||||
<StatStrip
|
||||
className="md:grid-cols-5"
|
||||
items={[
|
||||
{ label: 'Total', value: clients.length },
|
||||
{ label: 'Online', value: onlineCount, dot: 'ok' },
|
||||
{ label: 'Offline', value: offlineCount, dot: 'off' },
|
||||
{ label: 'Pending', value: pendingCount, dot: 'pending' },
|
||||
{ label: 'Revoked', value: revokedCount, dot: 'off' },
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -109,6 +121,7 @@ export default function ClientsPage() {
|
||||
online: onlineCount,
|
||||
offline: offlineCount,
|
||||
pending: pendingCount,
|
||||
revoked: revokedCount,
|
||||
}}
|
||||
/>
|
||||
<ClientsTable
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { AlertTriangle, RotateCcw } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function VconErrorBoundary({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
console.error('Admin console error boundary:', error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-[60vh] items-center justify-center p-4 text-[var(--text)]">
|
||||
<section className="w-full max-w-[440px] border border-[var(--border-strong)] bg-[var(--surface)] p-5">
|
||||
<div className="mb-3 flex items-center gap-2 border-b border-[var(--border)] pb-3">
|
||||
<AlertTriangle className="h-4 w-4 shrink-0 text-[var(--danger)]" aria-hidden="true" />
|
||||
<h1 className="text-[13px] font-medium uppercase tracking-wider text-[var(--text)]">
|
||||
Console panel error
|
||||
</h1>
|
||||
</div>
|
||||
<p className="mb-3 text-[12px] leading-relaxed text-[var(--text-muted)]">
|
||||
This console view encountered an unexpected failure. Retry rendering or navigate back to the dashboard.
|
||||
</p>
|
||||
{error?.message && (
|
||||
<div className="mb-4 border border-[var(--border)] bg-[var(--bg-main)] px-2.5 py-2 font-mono text-[11px] text-[var(--danger)] break-words">
|
||||
{error.message}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 border-t border-[var(--border)] pt-3">
|
||||
<Link href="/vcon/dashboard">
|
||||
<Button type="button" size="xs" variant="ghost">
|
||||
Dashboard
|
||||
</Button>
|
||||
</Link>
|
||||
<Button type="button" size="xs" variant="primary" onClick={() => reset()}>
|
||||
<RotateCcw className="h-3 w-3" aria-hidden="true" />
|
||||
Retry panel
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,12 +6,13 @@ export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function LoginPage() {
|
||||
if (process.env.DATABASE_URL) {
|
||||
const isConfigured = await isAdminSetupComplete().catch(() => false);
|
||||
if (!isConfigured) redirect('/vcon/setup');
|
||||
}
|
||||
const isConfigured = await isAdminSetupComplete().catch(() => false);
|
||||
if (!isConfigured) redirect('/vcon/setup');
|
||||
|
||||
const showDemoHint = !process.env.DATABASE_URL && process.env.NODE_ENV !== 'production';
|
||||
const showDemoHint =
|
||||
!process.env.DATABASE_URL &&
|
||||
process.env.NODE_ENV !== 'production' &&
|
||||
process.env.DATASTACK_ALLOW_DEMO_ADMIN !== 'false';
|
||||
|
||||
return <AdminLogin showDemoHint={showDemoHint} />;
|
||||
}
|
||||
+96
-21
@@ -11,15 +11,25 @@ import { useToast } from '@/components/ui/Toast';
|
||||
import { getCached, setCached } from '@/lib/vconCache';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface SdkClientItem {
|
||||
clientId: string;
|
||||
name: string;
|
||||
status?: 'active' | 'revoked';
|
||||
tokenPreview?: string;
|
||||
token?: string;
|
||||
}
|
||||
|
||||
export default function SdkGuidePage() {
|
||||
const { success } = useToast();
|
||||
const [clients, setClients] = useState<any[]>(() =>
|
||||
getCached<any[]>('vcon:clients', [])
|
||||
const { success, error } = useToast();
|
||||
const [clients, setClients] = useState<SdkClientItem[]>(() =>
|
||||
getCached<SdkClientItem[]>('vcon:clients', [])
|
||||
);
|
||||
const [selectedClientId, setSelectedClientId] = useState<string>(() => {
|
||||
const cached = getCached<any[]>('vcon:clients', []);
|
||||
return cached[0]?.clientId ?? '';
|
||||
const cached = getCached<SdkClientItem[]>('vcon:clients', []);
|
||||
return cached.find((c) => c.status !== 'revoked')?.clientId ?? cached[0]?.clientId ?? '';
|
||||
});
|
||||
const [selectedClientToken, setSelectedClientToken] = useState<string>('');
|
||||
const [loadingToken, setLoadingToken] = useState<boolean>(false);
|
||||
const [serverUrl, setServerUrl] = useState<string>('http://localhost:4000');
|
||||
const [apiUrl, setApiUrl] = useState<string>('http://localhost:3000');
|
||||
|
||||
@@ -34,33 +44,81 @@ export default function SdkGuidePage() {
|
||||
|
||||
async function loadClients() {
|
||||
try {
|
||||
const res = await fetch('/api/clients');
|
||||
const res = await fetch('/api/clients', { cache: 'no-store' });
|
||||
if (res.status === 401) {
|
||||
window.location.assign('/vcon/login');
|
||||
return;
|
||||
}
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const list = setCached('vcon:clients', data.clients || []);
|
||||
const list = setCached<SdkClientItem[]>('vcon:clients', data.clients || []);
|
||||
setClients(list);
|
||||
if (list.length > 0) {
|
||||
setSelectedClientId((prev) =>
|
||||
list.some((c: any) => c.clientId === prev) ? prev : list[0].clientId
|
||||
list.some((c) => c.clientId === prev)
|
||||
? prev
|
||||
: list.find((c) => c.status !== 'revoked')?.clientId ?? list[0].clientId
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
// Retain cached list on transient network error
|
||||
}
|
||||
}
|
||||
loadClients();
|
||||
void loadClients();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedClientId) {
|
||||
setSelectedClientToken('');
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setLoadingToken(true);
|
||||
|
||||
async function fetchToken() {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/clients/${encodeURIComponent(selectedClientId)}?includeToken=true`,
|
||||
{ cache: 'no-store' }
|
||||
);
|
||||
if (res.status === 401) {
|
||||
window.location.assign('/vcon/login');
|
||||
return;
|
||||
}
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (!cancelled) {
|
||||
setSelectedClientToken(String(data?.client?.token || ''));
|
||||
}
|
||||
} else if (!cancelled) {
|
||||
setSelectedClientToken('');
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setSelectedClientToken('');
|
||||
} finally {
|
||||
if (!cancelled) setLoadingToken(false);
|
||||
}
|
||||
}
|
||||
|
||||
void fetchToken();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedClientId]);
|
||||
|
||||
const activeClient =
|
||||
clients.find((c) => c.clientId === selectedClientId) || clients[0];
|
||||
const sampleToken = activeClient?.token || 'YOUR_SIGNED_CLIENT_JWT_TOKEN';
|
||||
const resolvedToken = selectedClientToken || activeClient?.token || '';
|
||||
const sampleToken = resolvedToken || 'YOUR_SIGNED_CLIENT_JWT_TOKEN';
|
||||
|
||||
const configSnippet = `# config.datastack.py — Place in your Python project root
|
||||
DATASTACK_CONFIG = {
|
||||
"SERVER_URL": "${serverUrl}",
|
||||
"API_URL": "${apiUrl}",
|
||||
"CLIENT_TOKEN": "${sampleToken}",
|
||||
"CLIENT_ID": "${activeClient?.clientId || ''}",
|
||||
"AUTO_CONNECT": True,
|
||||
"ENABLE_HTTP_FALLBACK": True,
|
||||
"HEARTBEAT_INTERVAL_SEC": 5.0,
|
||||
@@ -99,9 +157,21 @@ print("SDK Status:", client.status())
|
||||
|
||||
client.disconnect()`;
|
||||
|
||||
const copySnippet = (text: string, label: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
success('Copied', `${label} copied`);
|
||||
const copySnippet = async (text: string, label: string) => {
|
||||
try {
|
||||
if (!navigator?.clipboard?.writeText) {
|
||||
throw new Error('Clipboard API unavailable in this browser context');
|
||||
}
|
||||
await navigator.clipboard.writeText(text);
|
||||
success('Copied', `${label} copied`);
|
||||
} catch (copyErr) {
|
||||
error(
|
||||
'Copy failed',
|
||||
copyErr instanceof Error
|
||||
? copyErr.message
|
||||
: 'Unable to copy to clipboard. Copy manually from the code block.'
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -109,12 +179,13 @@ client.disconnect()`;
|
||||
title="Python SDK"
|
||||
actions={
|
||||
<>
|
||||
{activeClient?.token && (
|
||||
{resolvedToken && (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="secondary"
|
||||
icon="Key"
|
||||
onClick={() => copySnippet(activeClient.token, 'Client JWT token')}
|
||||
disabled={loadingToken}
|
||||
onClick={() => void copySnippet(resolvedToken, 'Client JWT token')}
|
||||
>
|
||||
Copy Token
|
||||
</Button>
|
||||
@@ -123,7 +194,7 @@ client.disconnect()`;
|
||||
size="xs"
|
||||
variant="secondary"
|
||||
icon="FileCode"
|
||||
onClick={() => copySnippet(configSnippet, 'config.datastack.py')}
|
||||
onClick={() => void copySnippet(configSnippet, 'config.datastack.py')}
|
||||
>
|
||||
Copy Config
|
||||
</Button>
|
||||
@@ -131,7 +202,7 @@ client.disconnect()`;
|
||||
size="xs"
|
||||
variant="secondary"
|
||||
icon="Copy"
|
||||
onClick={() => copySnippet(pythonSnippet, 'Python SDK snippet')}
|
||||
onClick={() => void copySnippet(pythonSnippet, 'Python SDK snippet')}
|
||||
>
|
||||
Copy Code
|
||||
</Button>
|
||||
@@ -161,8 +232,9 @@ client.disconnect()`;
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
aria-label="Copy pip install command"
|
||||
onClick={() =>
|
||||
copySnippet('pip install ./sdk/python/datastack', 'Pip command')
|
||||
void copySnippet('pip install ./sdk/python/datastack', 'Pip command')
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
@@ -176,6 +248,7 @@ client.disconnect()`;
|
||||
<div className="w-[190px]">
|
||||
<Select
|
||||
compact
|
||||
aria-label="Select SDK client"
|
||||
value={selectedClientId}
|
||||
onChange={(e) => setSelectedClientId(e.target.value)}
|
||||
>
|
||||
@@ -191,7 +264,8 @@ client.disconnect()`;
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
onClick={() => copySnippet(configSnippet, 'config.datastack.py')}
|
||||
aria-label="Copy config.datastack.py"
|
||||
onClick={() => void copySnippet(configSnippet, 'config.datastack.py')}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
@@ -207,7 +281,8 @@ client.disconnect()`;
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
onClick={() => copySnippet(pythonSnippet, 'Python SDK snippet')}
|
||||
aria-label="Copy Python SDK snippet"
|
||||
onClick={() => void copySnippet(pythonSnippet, 'Python SDK snippet')}
|
||||
/>
|
||||
}
|
||||
>
|
||||
|
||||
+310
-43
@@ -5,20 +5,40 @@ import { Button } from '@/components/ui/Button';
|
||||
import { CodeBlock } from '@/components/ui/CodeBlock';
|
||||
import { Select, Textarea } from '@/components/ui/Input';
|
||||
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 Link from 'next/link';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { io } from 'socket.io-client';
|
||||
|
||||
interface SimulatorClient {
|
||||
clientId: string;
|
||||
name: string;
|
||||
status: 'active' | 'revoked';
|
||||
}
|
||||
|
||||
type TransportMode = 'http' | 'websocket';
|
||||
type DispatchStatus = 'Ready' | 'Accepted' | 'Rejected' | 'Error';
|
||||
|
||||
function getSocketOrigin(): string {
|
||||
const isLocalDev = window.location.port === '3000';
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
const host = isLocalDev ? `${window.location.hostname}:4000` : window.location.host;
|
||||
return `${protocol}://${host}`;
|
||||
}
|
||||
|
||||
export default function SimulatorPage() {
|
||||
const { success, error } = useToast();
|
||||
const [clients, setClients] = useState<any[]>(() =>
|
||||
getCached<any[]>('vcon:clients', [])
|
||||
const { success, warning, error } = useToast();
|
||||
const [clients, setClients] = useState<SimulatorClient[]>(() =>
|
||||
getCached<SimulatorClient[]>('vcon:clients', [])
|
||||
);
|
||||
const [selectedClient, setSelectedClient] = useState<string>(() => {
|
||||
const cached = getCached<any[]>('vcon:clients', []);
|
||||
return cached[0]?.clientId ?? '';
|
||||
const cached = getCached<SimulatorClient[]>('vcon:clients', []);
|
||||
return cached.find((c) => c.status === 'active')?.clientId ?? cached[0]?.clientId ?? '';
|
||||
});
|
||||
const [transport, setTransport] = useState<TransportMode>('http');
|
||||
const [payloadText, setPayloadText] = useState<string>(
|
||||
JSON.stringify(
|
||||
{
|
||||
@@ -33,30 +53,136 @@ export default function SimulatorPage() {
|
||||
)
|
||||
);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [lastResponse, setLastResponse] = useState<any>(null);
|
||||
const [dispatchStatus, setDispatchStatus] = useState<DispatchStatus>('Ready');
|
||||
const [lastResponse, setLastResponse] = useState<Record<string, unknown> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadClients() {
|
||||
try {
|
||||
const res = await fetch('/api/clients');
|
||||
const res = await fetch('/api/clients', { cache: 'no-store' });
|
||||
if (res.status === 401) {
|
||||
window.location.assign('/vcon/login');
|
||||
return;
|
||||
}
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const list = setCached('vcon:clients', data.clients || []);
|
||||
const list = setCached<SimulatorClient[]>('vcon:clients', data.clients || []);
|
||||
setClients(list);
|
||||
if (list.length > 0)
|
||||
setSelectedClient((prev) => prev || list[0].clientId);
|
||||
setSelectedClient((prev) => {
|
||||
if (prev && list.some((c) => c.clientId === prev)) return prev;
|
||||
return list.find((c) => c.status === 'active')?.clientId ?? list[0]?.clientId ?? '';
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
// Ignore transient failure and retain cached list
|
||||
}
|
||||
}
|
||||
loadClients();
|
||||
void loadClients();
|
||||
}, []);
|
||||
|
||||
const fetchClientJwt = async (clientId: string): Promise<string> => {
|
||||
const res = await fetch(`/api/clients/${encodeURIComponent(clientId)}?includeToken=true`, {
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (res.status === 401) {
|
||||
window.location.assign('/vcon/login');
|
||||
throw new Error('Authentication required');
|
||||
}
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data?.client?.token) {
|
||||
throw new Error(data?.error || 'Unable to retrieve client JWT token');
|
||||
}
|
||||
return String(data.client.token);
|
||||
};
|
||||
|
||||
const emitSocketEvents = async (
|
||||
clientId: string,
|
||||
items: Array<Record<string, unknown>>
|
||||
): Promise<{ accepted: number; rejected: number; responses: Record<string, unknown>[] }> => {
|
||||
const token = await fetchClientJwt(clientId);
|
||||
const socketUrl = getSocketOrigin();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = io(socketUrl, {
|
||||
auth: { token },
|
||||
transports: ['websocket', 'polling'],
|
||||
reconnection: false,
|
||||
timeout: 4000,
|
||||
});
|
||||
|
||||
const timer = window.setTimeout(() => {
|
||||
socket.disconnect();
|
||||
reject(new Error('WebSocket handshake timed out (is Port 4000 ingestion server running?)'));
|
||||
}, 4500);
|
||||
|
||||
socket.on('connect_error', (connectErr) => {
|
||||
window.clearTimeout(timer);
|
||||
socket.disconnect();
|
||||
reject(new Error(connectErr.message || 'WebSocket authentication failed'));
|
||||
});
|
||||
|
||||
socket.on('connect', () => {
|
||||
const responses: Record<string, unknown>[] = [];
|
||||
let accepted = 0;
|
||||
let rejected = 0;
|
||||
let settled = 0;
|
||||
|
||||
const finishIfDone = () => {
|
||||
if (settled >= items.length) {
|
||||
window.clearTimeout(timer);
|
||||
socket.disconnect();
|
||||
resolve({ accepted, rejected, responses });
|
||||
}
|
||||
};
|
||||
|
||||
const onAck = (ack: Record<string, unknown>) => {
|
||||
responses.push(ack);
|
||||
if (ack?.status === 'ok' || ack?.status === 'duplicate') {
|
||||
accepted++;
|
||||
} else {
|
||||
rejected++;
|
||||
}
|
||||
settled++;
|
||||
finishIfDone();
|
||||
};
|
||||
|
||||
const onErrorEvent = (errPayload: Record<string, unknown>) => {
|
||||
responses.push(errPayload);
|
||||
rejected++;
|
||||
settled++;
|
||||
finishIfDone();
|
||||
};
|
||||
|
||||
socket.on('ack', onAck);
|
||||
socket.on('error_event', onErrorEvent);
|
||||
|
||||
items.forEach((data, index) => {
|
||||
const eventId = `sim_ws_${Date.now()}_${index}`;
|
||||
socket.emit('telemetry_event', {
|
||||
clientId,
|
||||
eventId,
|
||||
timestamp: new Date().toISOString(),
|
||||
data,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const handleSendSingle = async () => {
|
||||
let parsedData: any;
|
||||
if (!selectedClient) {
|
||||
error('No target client', 'Register a client in /vcon/clients first.');
|
||||
return;
|
||||
}
|
||||
|
||||
let parsedData: Record<string, unknown>;
|
||||
try {
|
||||
parsedData = JSON.parse(payloadText);
|
||||
const raw = JSON.parse(payloadText);
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
error('Invalid payload', 'Payload must be a JSON object.');
|
||||
return;
|
||||
}
|
||||
parsedData = raw as Record<string, unknown>;
|
||||
} catch {
|
||||
error('Invalid JSON', 'Fix payload syntax');
|
||||
return;
|
||||
@@ -64,54 +190,145 @@ export default function SimulatorPage() {
|
||||
|
||||
setSending(true);
|
||||
try {
|
||||
if (transport === 'websocket') {
|
||||
const result = await emitSocketEvents(selectedClient, [parsedData]);
|
||||
const first = result.responses[0] || {};
|
||||
setLastResponse({ transport: 'websocket', ...first });
|
||||
if (result.accepted > 0) {
|
||||
setDispatchStatus('Accepted');
|
||||
success('WebSocket Event Accepted', `${String(first.eventId || selectedClient)} acknowledged`);
|
||||
} else {
|
||||
setDispatchStatus('Rejected');
|
||||
error('WebSocket Event Rejected', String(first.message || first.error || 'Rejected by Port 4000'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch('/api/events', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
clientId: selectedClient || 'py_telemetry_agent_01',
|
||||
clientId: selectedClient,
|
||||
data: parsedData,
|
||||
}),
|
||||
});
|
||||
if (res.status === 401) {
|
||||
window.location.assign('/vcon/login');
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
setLastResponse(data);
|
||||
setLastResponse({ transport: 'http', status: res.status, ...data });
|
||||
|
||||
if (res.ok) {
|
||||
success('Event Accepted', `${data.event.eventId} buffered`);
|
||||
setDispatchStatus('Accepted');
|
||||
success('Event Accepted', `${data.event?.eventId || selectedClient} buffered`);
|
||||
} else {
|
||||
setDispatchStatus('Rejected');
|
||||
error('Event Rejected', data.error || 'Server rejected');
|
||||
}
|
||||
} catch (err: any) {
|
||||
error('Error', err.message);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Dispatch error';
|
||||
setDispatchStatus('Error');
|
||||
setLastResponse({ transport, error: message });
|
||||
error('Dispatch failed', message);
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSendBatch = async (count = 10) => {
|
||||
if (!selectedClient) {
|
||||
error('No target client', 'Register a client in /vcon/clients first.');
|
||||
return;
|
||||
}
|
||||
|
||||
const items = Array.from({ length: count }, (_, i) => ({
|
||||
batch_index: i + 1,
|
||||
sensor: `sensor_${(i % 3) + 1}`,
|
||||
reading: +(Math.random() * 100).toFixed(2),
|
||||
timestamp: new Date().toISOString(),
|
||||
}));
|
||||
|
||||
setSending(true);
|
||||
try {
|
||||
if (transport === 'websocket') {
|
||||
const result = await emitSocketEvents(selectedClient, items);
|
||||
setLastResponse({
|
||||
transport: 'websocket',
|
||||
batchSent: count,
|
||||
accepted: result.accepted,
|
||||
rejected: result.rejected,
|
||||
sample: result.responses.slice(0, 3),
|
||||
});
|
||||
if (result.accepted === 0) {
|
||||
setDispatchStatus('Rejected');
|
||||
error('WebSocket Batch Rejected', `0/${count} events ingested`);
|
||||
} else if (result.accepted < count) {
|
||||
setDispatchStatus('Rejected');
|
||||
warning('WebSocket Batch Partial', `${result.accepted}/${count} ingested (${result.rejected} rejected)`);
|
||||
} else {
|
||||
setDispatchStatus('Accepted');
|
||||
success('WebSocket Batch Streamed', `${result.accepted}/${count} ingested`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let accepted = 0;
|
||||
for (let i = 0; i < count; i++) {
|
||||
let rejected = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
const res = await fetch('/api/events', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
clientId: selectedClient || 'py_telemetry_agent_01',
|
||||
data: {
|
||||
batch_index: i + 1,
|
||||
sensor: `sensor_${(i % 3) + 1}`,
|
||||
reading: +(Math.random() * 100).toFixed(2),
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
clientId: selectedClient,
|
||||
data: item,
|
||||
}),
|
||||
});
|
||||
if (res.ok) accepted++;
|
||||
if (res.status === 401) {
|
||||
window.location.assign('/vcon/login');
|
||||
return;
|
||||
}
|
||||
if (res.ok) {
|
||||
accepted++;
|
||||
} else {
|
||||
rejected++;
|
||||
try {
|
||||
const errJson = await res.json();
|
||||
if (errJson?.error && errors.length < 3) {
|
||||
errors.push(String(errJson.error));
|
||||
}
|
||||
} catch {
|
||||
// ignore non-json error body
|
||||
}
|
||||
}
|
||||
}
|
||||
success('Batch Streamed', `${accepted}/${count} ingested`);
|
||||
setLastResponse({ success: true, batchSent: count, accepted });
|
||||
} catch (err: any) {
|
||||
error('Batch Error', err.message);
|
||||
|
||||
setLastResponse({
|
||||
transport: 'http',
|
||||
batchSent: count,
|
||||
accepted,
|
||||
rejected,
|
||||
...(errors.length > 0 ? { errors } : {}),
|
||||
});
|
||||
|
||||
if (accepted === 0) {
|
||||
setDispatchStatus('Rejected');
|
||||
error('Batch Rejected', `0/${count} ingested${errors[0] ? ` (${errors[0]})` : ''}`);
|
||||
} else if (accepted < count) {
|
||||
setDispatchStatus('Rejected');
|
||||
warning('Batch Partial', `${accepted}/${count} ingested (${rejected} rejected)`);
|
||||
} else {
|
||||
setDispatchStatus('Accepted');
|
||||
success('Batch Streamed', `${accepted}/${count} ingested`);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Batch dispatch error';
|
||||
setDispatchStatus('Error');
|
||||
setLastResponse({ transport, error: message });
|
||||
error('Batch Error', message);
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
@@ -126,7 +343,8 @@ export default function SimulatorPage() {
|
||||
size="xs"
|
||||
variant="secondary"
|
||||
loading={sending}
|
||||
onClick={() => handleSendBatch(10)}
|
||||
disabled={sending || !selectedClient}
|
||||
onClick={() => void handleSendBatch(10)}
|
||||
>
|
||||
Burst 10
|
||||
</Button>
|
||||
@@ -135,44 +353,93 @@ export default function SimulatorPage() {
|
||||
variant="primary"
|
||||
icon="Send"
|
||||
loading={sending}
|
||||
onClick={handleSendSingle}
|
||||
disabled={sending || !selectedClient}
|
||||
onClick={() => void handleSendSingle()}
|
||||
>
|
||||
Send Event
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{clients.length === 0 && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex flex-wrap items-center justify-between gap-2 border border-[var(--warning)] bg-[var(--warning-soft)] px-3 py-2 text-[11.5px] text-[var(--text)]"
|
||||
>
|
||||
<span>No registered SDK clients found. Register a client before dispatching events.</span>
|
||||
<Link href="/vcon/clients" className="font-medium text-[var(--accent)] underline">
|
||||
Go to Clients →
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<StatStrip
|
||||
items={[
|
||||
{
|
||||
label: 'Target client',
|
||||
value: selectedClient || 'py_telemetry_agent_01',
|
||||
dot: 'ok',
|
||||
value: selectedClient || 'None selected',
|
||||
dot: selectedClient ? 'ok' : 'off',
|
||||
},
|
||||
{
|
||||
label: 'Ingest transport',
|
||||
value: transport === 'http' ? 'POST /api/events' : 'WS Port 4000',
|
||||
},
|
||||
{ label: 'Ingest route', value: 'POST /api/events' },
|
||||
{ label: 'Payload format', value: 'JSON' },
|
||||
{
|
||||
label: 'Last dispatch',
|
||||
value: lastResponse ? 'Accepted' : 'Ready',
|
||||
value: dispatchStatus,
|
||||
dot:
|
||||
dispatchStatus === 'Accepted'
|
||||
? 'ok'
|
||||
: dispatchStatus === 'Ready'
|
||||
? undefined
|
||||
: 'off',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
|
||||
<Panel title="Payload" bodyClassName="flex flex-col gap-2.5 p-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
|
||||
Transport
|
||||
</span>
|
||||
<div className="flex gap-1" role="group" aria-label="Ingest transport">
|
||||
<Pill
|
||||
active={transport === 'http'}
|
||||
onClick={() => setTransport('http')}
|
||||
>
|
||||
HTTP /api/events
|
||||
</Pill>
|
||||
<Pill
|
||||
active={transport === 'websocket'}
|
||||
onClick={() => setTransport('websocket')}
|
||||
>
|
||||
WebSocket Port 4000
|
||||
</Pill>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Select
|
||||
compact
|
||||
label="Target client"
|
||||
value={selectedClient}
|
||||
disabled={clients.length === 0}
|
||||
onChange={(e) => setSelectedClient(e.target.value)}
|
||||
>
|
||||
{clients.map((c) => (
|
||||
<option key={c.clientId} value={c.clientId}>
|
||||
{c.clientId}
|
||||
</option>
|
||||
))}
|
||||
{clients.length === 0 ? (
|
||||
<option value="">No registered clients</option>
|
||||
) : (
|
||||
clients.map((c) => (
|
||||
<option key={c.clientId} value={c.clientId}>
|
||||
{c.clientId} ({c.status})
|
||||
</option>
|
||||
))
|
||||
)}
|
||||
</Select>
|
||||
|
||||
<Textarea
|
||||
label="Event JSON"
|
||||
rows={7}
|
||||
value={payloadText}
|
||||
onChange={(e) => setPayloadText(e.target.value)}
|
||||
|
||||
Reference in new issue
Block a user