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:
1 parent
d39d9f92f9
commit
fcc4f4db2d
88 files changed
+21248
-2213
No files matched your search
@@ -0,0 +1,16 @@
|
||||
import { MainLayout } from '@/components/layout/MainLayout';
|
||||
import { Features } from '@/components/sections/Features';
|
||||
import { Hero } from '@/components/sections/Hero';
|
||||
import { LandingAbout } from '@/components/sections/LandingAbout';
|
||||
import { SdkSection } from '@/components/sections/SdkSection';
|
||||
|
||||
export default function LandingPage() {
|
||||
return (
|
||||
<MainLayout>
|
||||
<Hero />
|
||||
<Features />
|
||||
<SdkSection />
|
||||
<LandingAbout />
|
||||
</MainLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { createAdminSessionToken } from "@/core/auth/adminSession";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
const SESSION_SECONDS = 8 * 60 * 60;
|
||||
const REMEMBERED_SESSION_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
function constantTimeEqual(left: string, right: string) {
|
||||
const leftHash = createHash("sha256").update(left).digest();
|
||||
const rightHash = createHash("sha256").update(right).digest();
|
||||
return timingSafeEqual(leftHash, rightHash);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const adminEmail = process.env.DATASTACK_ADMIN_EMAIL;
|
||||
const adminPassword = process.env.DATASTACK_ADMIN_PASSWORD;
|
||||
const sessionSecret = process.env.DATASTACK_ADMIN_SESSION_SECRET;
|
||||
|
||||
if (
|
||||
!adminEmail ||
|
||||
!adminPassword ||
|
||||
!sessionSecret ||
|
||||
sessionSecret.length < 32
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Admin login is not configured. Set the required server environment variables.",
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const email =
|
||||
typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
||||
const password = typeof body.password === "string" ? body.password : "";
|
||||
|
||||
if (
|
||||
!constantTimeEqual(email, adminEmail.trim().toLowerCase()) ||
|
||||
!constantTimeEqual(password, adminPassword)
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
const remember = body.remember === true;
|
||||
const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS;
|
||||
const expiresAt = Date.now() + maxAge * 1000;
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
sessionSecret,
|
||||
expiresAt,
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
|
||||
response.cookies.set(SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "strict",
|
||||
path: "/",
|
||||
maxAge,
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid login request." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,58 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { SDKManager } from '@/core/sdk/sdkManager';
|
||||
import { SDKManager } from "@/core/sdk/sdkManager";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function GET(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const { id } = await params;
|
||||
const client = SDKManager.getClient(id);
|
||||
if (!client) {
|
||||
return NextResponse.json({ error: 'Client not found' }, { status: 404 });
|
||||
return NextResponse.json({ error: "Client not found" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ client });
|
||||
const { secret, token, ...clientSummary } = client;
|
||||
return NextResponse.json({ client: clientSummary });
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const body = await req.json();
|
||||
|
||||
// Special action: regenerate token
|
||||
if (body.action === 'regenerate_token') {
|
||||
if (body.action === "regenerate_token") {
|
||||
const refreshed = SDKManager.regenerateToken(id);
|
||||
if (!refreshed) {
|
||||
return NextResponse.json({ error: 'Client not found' }, { status: 404 });
|
||||
return NextResponse.json(
|
||||
{ error: "Client not found" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ client: refreshed });
|
||||
}
|
||||
|
||||
const updated = SDKManager.updateClient(id, body);
|
||||
if (!updated) {
|
||||
return NextResponse.json({ error: 'Client not found' }, { status: 404 });
|
||||
return NextResponse.json({ error: "Client not found" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ client: updated });
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Update failed';
|
||||
const message = err instanceof Error ? err.message : "Update failed";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const { id } = await params;
|
||||
const deleted = SDKManager.deleteClient(id);
|
||||
if (!deleted) {
|
||||
return NextResponse.json({ error: 'Client not found' }, { status: 404 });
|
||||
return NextResponse.json({ error: "Client not found" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ success: true, message: `Client ${id} deleted` });
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { SDKManager } from '@/core/sdk/sdkManager';
|
||||
import { SDKManager } from "@/core/sdk/sdkManager";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const clients = SDKManager.listClients();
|
||||
const clients = SDKManager.listClients().map(
|
||||
({ secret, token, ...client }) => client,
|
||||
);
|
||||
return NextResponse.json({ clients, count: clients.length });
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to list clients';
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Failed to list clients";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -18,8 +21,8 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
if (!clientId || !name) {
|
||||
return NextResponse.json(
|
||||
{ error: 'clientId and name are required' },
|
||||
{ status: 400 }
|
||||
{ error: "clientId and name are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,7 +30,7 @@ export async function POST(req: NextRequest) {
|
||||
if (existing) {
|
||||
return NextResponse.json(
|
||||
{ error: `Client '${clientId}' already exists` },
|
||||
{ status: 409 }
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -39,7 +42,8 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
return NextResponse.json({ client: newClient }, { status: 201 });
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Client creation failed';
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Client creation failed";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { DataBufferEngine } from "@/core/data/buffer";
|
||||
import { CSVStorageManager } from "@/core/Storage/csvStorage";
|
||||
import { parse } from "csv-parse";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createReadStream, readdirSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
interface DataEvent {
|
||||
clientId: string;
|
||||
eventId: string;
|
||||
timestamp: string;
|
||||
payload: string;
|
||||
status: "stored" | "buffered";
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const clientId = searchParams.get("clientId") || "all";
|
||||
const from = searchParams.get("from") || "";
|
||||
const to = searchParams.get("to") || "";
|
||||
const search = (searchParams.get("search") || "").toLowerCase();
|
||||
const page = Math.max(1, Number(searchParams.get("page")) || 1);
|
||||
const pageSize = Math.min(
|
||||
100,
|
||||
Math.max(1, Number(searchParams.get("pageSize")) || 12),
|
||||
);
|
||||
const offset = (page - 1) * pageSize;
|
||||
const selectedRows: DataEvent[] = [];
|
||||
const eventIds = new Set<string>();
|
||||
let total = 0;
|
||||
|
||||
const addIfMatching = (event: DataEvent) => {
|
||||
const eventDate = event.timestamp.slice(0, 10);
|
||||
if (
|
||||
(clientId !== "all" && event.clientId !== clientId) ||
|
||||
(from && eventDate < from) ||
|
||||
(to && eventDate > to) ||
|
||||
(search && !event.payload.toLowerCase().includes(search)) ||
|
||||
eventIds.has(event.eventId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
eventIds.add(event.eventId);
|
||||
total += 1;
|
||||
|
||||
let low = 0;
|
||||
let high = selectedRows.length;
|
||||
while (low < high) {
|
||||
const middle = (low + high) >>> 1;
|
||||
if (selectedRows[middle].timestamp >= event.timestamp) low = middle + 1;
|
||||
else high = middle;
|
||||
}
|
||||
|
||||
if (low < offset + pageSize) {
|
||||
selectedRows.splice(low, 0, event);
|
||||
if (selectedRows.length > offset + pageSize) selectedRows.pop();
|
||||
}
|
||||
};
|
||||
|
||||
const storageDir = CSVStorageManager.baseStorageDir;
|
||||
let clientDirs: string[] = [];
|
||||
try {
|
||||
clientDirs = readdirSync(storageDir);
|
||||
} catch {
|
||||
clientDirs = [];
|
||||
}
|
||||
|
||||
for (const storedClientId of clientDirs) {
|
||||
if (clientId !== "all" && storedClientId !== clientId) continue;
|
||||
|
||||
const clientDir = path.join(storageDir, storedClientId);
|
||||
if (!statSync(clientDir).isDirectory()) continue;
|
||||
|
||||
let filenames: string[];
|
||||
try {
|
||||
filenames = readdirSync(clientDir).filter((filename) =>
|
||||
/^\d{4}-\d{2}-\d{2}(?:-part\d+)?\.csv$/.test(filename),
|
||||
);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const filename of filenames) {
|
||||
const fileDate = filename.slice(0, 10);
|
||||
if ((from && fileDate < from) || (to && fileDate > to)) continue;
|
||||
|
||||
const parser = createReadStream(path.join(clientDir, filename)).pipe(
|
||||
parse({ columns: true, skip_empty_lines: true, bom: true }),
|
||||
);
|
||||
|
||||
try {
|
||||
for await (const record of parser as AsyncIterable<
|
||||
Record<string, string>
|
||||
>) {
|
||||
const event = {
|
||||
clientId: record.clientId || storedClientId,
|
||||
eventId: record.eventId || "",
|
||||
timestamp: record.timestamp || `${fileDate}T00:00:00.000Z`,
|
||||
payload: record.payload || "",
|
||||
status: "stored" as const,
|
||||
};
|
||||
if (event.eventId) addIfMatching(event);
|
||||
}
|
||||
} catch {
|
||||
parser.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const event of DataBufferEngine.getRecentEvents(200)) {
|
||||
addIfMatching({ ...event, status: "buffered" });
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
events: selectedRows.slice(offset),
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
pageCount: Math.max(1, Math.ceil(total / pageSize)),
|
||||
});
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Data retrieval failed";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
+146
-60
@@ -1,76 +1,162 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { CSVStorageManager } from '@/core/Storage/csvStorage';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import {
|
||||
CSVStorageManager,
|
||||
type StorageFileMeta,
|
||||
} from "@/core/Storage/csvStorage";
|
||||
import { parse } from "csv-parse";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createReadStream } from "node:fs";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const clientId = searchParams.get('clientId');
|
||||
const filename = searchParams.get('filename');
|
||||
type ExportFormat = "csv" | "json";
|
||||
type CsvRecord = Record<string, string>;
|
||||
type StreamChunk = string | Uint8Array;
|
||||
|
||||
// Single specific file export
|
||||
if (clientId && filename) {
|
||||
const content = CSVStorageManager.getFileContent(clientId, filename);
|
||||
if (!content) {
|
||||
return NextResponse.json({ error: 'CSV file not found' }, { status: 404 });
|
||||
}
|
||||
function toByteStream(chunks: AsyncIterable<StreamChunk>) {
|
||||
const iterator = chunks[Symbol.asyncIterator]();
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
return new NextResponse(content, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'text/csv; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Stream aggregate or list files
|
||||
const allFiles = CSVStorageManager.listAllFiles();
|
||||
const filtered = clientId && clientId !== 'all'
|
||||
? allFiles.filter((f) => f.clientId === clientId)
|
||||
: allFiles;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
const emptyCsv = 'clientId,eventId,timestamp,payload\n';
|
||||
return new NextResponse(emptyCsv, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'text/csv; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="datastack_export_${Date.now()}.csv"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Combine matching files with a single header
|
||||
let combined = 'clientId,eventId,timestamp,payload\n';
|
||||
for (const f of filtered) {
|
||||
return new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
try {
|
||||
const raw = fs.readFileSync(f.filePath, 'utf8');
|
||||
const lines = raw.split('\n');
|
||||
// skip header on subsequent lines
|
||||
const dataLines = lines.slice(1).filter((l) => l.trim().length > 0);
|
||||
if (dataLines.length > 0) {
|
||||
combined += dataLines.join('\n') + '\n';
|
||||
const result = await iterator.next();
|
||||
if (result.done) {
|
||||
controller.close();
|
||||
} else {
|
||||
controller.enqueue(
|
||||
typeof result.value === "string"
|
||||
? encoder.encode(result.value)
|
||||
: result.value,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// continue
|
||||
} catch (error) {
|
||||
controller.error(error);
|
||||
}
|
||||
},
|
||||
async cancel() {
|
||||
await iterator.return?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function* readFileRecords(
|
||||
file: StorageFileMeta,
|
||||
): AsyncGenerator<CsvRecord> {
|
||||
const parser = createReadStream(file.filePath).pipe(
|
||||
parse({ columns: true, skip_empty_lines: true, bom: true }),
|
||||
);
|
||||
|
||||
try {
|
||||
for await (const record of parser as AsyncIterable<CsvRecord>) {
|
||||
yield record;
|
||||
}
|
||||
} catch {
|
||||
parser.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
function makeExportStream(
|
||||
files: StorageFileMeta[],
|
||||
format: ExportFormat,
|
||||
includeHeader: boolean,
|
||||
) {
|
||||
const fields = ["clientId", "eventId", "timestamp", "payload"];
|
||||
const chunks = (async function* () {
|
||||
let isFirst = true;
|
||||
|
||||
if (format === "json") {
|
||||
yield "[";
|
||||
} else if (includeHeader) {
|
||||
yield `${fields.join(",")}\n`;
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
for await (const record of readFileRecords(file)) {
|
||||
if (format === "json") {
|
||||
const payload = record.payload ?? "";
|
||||
let parsedPayload: unknown = payload;
|
||||
try {
|
||||
parsedPayload = JSON.parse(payload);
|
||||
} catch {
|
||||
// Keep non-JSON payloads as strings.
|
||||
}
|
||||
yield `${isFirst ? "" : ","}${JSON.stringify({ ...record, payload: parsedPayload })}`;
|
||||
} else {
|
||||
const line = fields
|
||||
.map((field) => `"${(record[field] ?? "").replaceAll('"', '""')}"`)
|
||||
.join(",");
|
||||
yield `${line}\n`;
|
||||
}
|
||||
isFirst = false;
|
||||
}
|
||||
}
|
||||
|
||||
const exportFileName = clientId && clientId !== 'all'
|
||||
? `${clientId}_export_${new Date().toISOString().split('T')[0]}.csv`
|
||||
: `datastack_universal_export_${new Date().toISOString().split('T')[0]}.csv`;
|
||||
if (format === "json") yield "]";
|
||||
})();
|
||||
|
||||
return new NextResponse(combined, {
|
||||
return toByteStream(chunks);
|
||||
}
|
||||
|
||||
function streamFile(file: StorageFileMeta) {
|
||||
async function* chunks() {
|
||||
for await (const chunk of createReadStream(file.filePath)) {
|
||||
yield new Uint8Array(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
return toByteStream(chunks());
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const clientId = searchParams.get("clientId") || "all";
|
||||
const filename = searchParams.get("filename");
|
||||
const from = searchParams.get("from") || "";
|
||||
const to = searchParams.get("to") || "";
|
||||
const format: ExportFormat =
|
||||
searchParams.get("format") === "json" ? "json" : "csv";
|
||||
const includeHeader = searchParams.get("includeHeader") !== "false";
|
||||
|
||||
let files = CSVStorageManager.listAllFiles();
|
||||
if (clientId !== "all")
|
||||
files = files.filter((file) => file.clientId === clientId);
|
||||
|
||||
if (filename) {
|
||||
const file = files.find((candidate) => candidate.filename === filename);
|
||||
if (!file)
|
||||
return NextResponse.json(
|
||||
{ error: "CSV file not found" },
|
||||
{ status: 404 },
|
||||
);
|
||||
return new NextResponse(streamFile(file), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="${file.filename}"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
files = files.filter(
|
||||
(file) => (!from || file.date >= from) && (!to || file.date <= to),
|
||||
);
|
||||
const datePart = new Date().toISOString().slice(0, 10);
|
||||
const safeClientId = clientId.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
const baseName =
|
||||
clientId === "all" ? "datastack_export" : `${safeClientId}_export`;
|
||||
|
||||
return new NextResponse(makeExportStream(files, format, includeHeader), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'text/csv; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="${exportFileName}"`,
|
||||
"Content-Type":
|
||||
format === "json"
|
||||
? "application/json; charset=utf-8"
|
||||
: "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="${baseName}_${datePart}.${format}"`,
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Export failed';
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Export failed";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { SettingsManager } from '@/core/adminSettings/settingsManager';
|
||||
import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const settings = SettingsManager.getSettings();
|
||||
const settings = SettingsManager.getPublicSettings();
|
||||
return NextResponse.json({ settings });
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Settings read failed';
|
||||
const message = err instanceof Error ? err.message : "Settings read failed";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,14 @@ export async function GET() {
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json();
|
||||
const updated = SettingsManager.updateSettings(body);
|
||||
return NextResponse.json({ settings: updated, success: true });
|
||||
SettingsManager.updateSettings(body);
|
||||
return NextResponse.json({
|
||||
settings: SettingsManager.getPublicSettings(),
|
||||
success: true,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Settings update failed';
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Settings update failed";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
+80
-55
@@ -2,73 +2,89 @@
|
||||
|
||||
:root {
|
||||
--radius: 0rem;
|
||||
--font-weight-semibold: 500;
|
||||
--font-weight-bold: 500;
|
||||
--font-weight-extrabold: 500;
|
||||
--font-sans: "Segoe UI", "Segoe UI Web", system-ui, -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif;
|
||||
--font-mono: ui-monospace, "SF Mono", "Liberation Mono", Menlo, Consolas, monospace;
|
||||
--font-mono: "Consolas", "Courier New", monospace;
|
||||
--container-width: 1080px;
|
||||
--console-width: 1240px;
|
||||
--surface-3: #1d1d21;
|
||||
--accent-text: var(--accent);
|
||||
|
||||
/* Theme tokens - Dark Mode (Sleek Graphite Workbench) */
|
||||
--bg-main: #0c0e12;
|
||||
--bg-sidebar: #0f1117;
|
||||
--bg-activity: #131720;
|
||||
--bg-elevated: #161b24;
|
||||
--bg-hover: #1c2230;
|
||||
--bg-active: #242c3d;
|
||||
--border: #212836;
|
||||
--border-strong: #2e374a;
|
||||
--text: #e6ebf2;
|
||||
--text-muted: #8c96a8;
|
||||
--text-dim: #5c6577;
|
||||
--accent: #3b82f6;
|
||||
--accent-soft: rgba(59, 130, 246, 0.08);
|
||||
--accent-hover: #60a5fa;
|
||||
--text-on-accent: #ffffff;
|
||||
--success: #10b981;
|
||||
--success-soft: rgba(16, 185, 129, 0.08);
|
||||
--warning: #f59e0b;
|
||||
--warning-soft: rgba(245, 158, 11, 0.08);
|
||||
--danger: #ef4444;
|
||||
--danger-soft: rgba(239, 68, 68, 0.08);
|
||||
--bg: #0a0a0b;
|
||||
--surface: #111113;
|
||||
--surface-2: #17171a;
|
||||
--border: #232326;
|
||||
--border-strong: #2e2e33;
|
||||
--text: #e8e8ea;
|
||||
--text-muted: #85858c;
|
||||
--text-faint: #5a5a62;
|
||||
--accent: #a3e635;
|
||||
--accent-soft: rgba(163, 230, 53, 0.08);
|
||||
--font: var(--font-sans);
|
||||
--radius: 0rem;
|
||||
--bg-main: var(--bg);
|
||||
--bg-sidebar: var(--surface);
|
||||
--bg-activity: var(--surface);
|
||||
--bg-elevated: var(--surface);
|
||||
--bg-hover: var(--surface-2);
|
||||
--bg-active: var(--surface-2);
|
||||
--text-dim: var(--text-faint);
|
||||
--accent-hover: var(--accent);
|
||||
--text-on-accent: var(--bg);
|
||||
--success: var(--accent);
|
||||
--success-soft: var(--accent-soft);
|
||||
--warning: var(--text-muted);
|
||||
--warning-soft: transparent;
|
||||
--danger: var(--text-muted);
|
||||
--danger-soft: transparent;
|
||||
}
|
||||
|
||||
html.light, body.light {
|
||||
/* Theme tokens - Light Mode (Clean, soft contrast) */
|
||||
--bg-main: #ffffff;
|
||||
--bg-sidebar: #f8fafc;
|
||||
--bg-activity: #f1f5f9;
|
||||
--bg-elevated: #ffffff;
|
||||
--bg-hover: #f1f5f9;
|
||||
--bg-active: #e2e8f0;
|
||||
--border: #e2e8f0;
|
||||
--border-strong: #cbd5e1;
|
||||
--text: #0f172a;
|
||||
--text-muted: #475569;
|
||||
--text-dim: #94a3b8;
|
||||
--accent: #2563eb;
|
||||
--accent-soft: rgba(37, 99, 235, 0.06);
|
||||
--accent-hover: #1d4ed8;
|
||||
--text-on-accent: #ffffff;
|
||||
--success: #059669;
|
||||
--success-soft: rgba(5, 150, 105, 0.08);
|
||||
--warning: #d97706;
|
||||
--warning-soft: rgba(217, 119, 6, 0.08);
|
||||
--danger: #dc2626;
|
||||
--danger-soft: rgba(220, 38, 38, 0.08);
|
||||
--bg: #fafafa;
|
||||
--surface: #f4f4f5;
|
||||
--surface-2: #ececed;
|
||||
--surface-3: #ececed;
|
||||
--border: #e2e2e5;
|
||||
--border-strong: #d0d0d3;
|
||||
--text: #111113;
|
||||
--text-muted: #5a5a62;
|
||||
--text-faint: #85858c;
|
||||
--accent: #65a30d;
|
||||
--accent-soft: rgba(101, 163, 13, 0.08);
|
||||
--accent-text: #4d7c0f;
|
||||
--font: var(--font-sans);
|
||||
--bg-main: var(--bg);
|
||||
--bg-sidebar: var(--surface);
|
||||
--bg-activity: var(--surface);
|
||||
--bg-elevated: var(--surface);
|
||||
--bg-hover: var(--surface-2);
|
||||
--bg-active: var(--surface-2);
|
||||
--text-dim: var(--text-faint);
|
||||
--accent-hover: var(--accent);
|
||||
--text-on-accent: var(--bg);
|
||||
--success: var(--accent);
|
||||
--success-soft: var(--accent-soft);
|
||||
--warning: var(--text-muted);
|
||||
--warning-soft: transparent;
|
||||
--danger: var(--text-muted);
|
||||
--danger-soft: transparent;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border-radius: 0 !important;
|
||||
box-shadow: none !important;
|
||||
text-shadow: none !important;
|
||||
}
|
||||
|
||||
html, body {
|
||||
font-family: var(--font-sans) !important;
|
||||
font-family: var(--font) !important;
|
||||
background-color: var(--bg-main);
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
@@ -82,7 +98,11 @@ h1, h2, h3, h4, h5, h6 {
|
||||
font-family: var(--font-sans) !important;
|
||||
font-weight: 500;
|
||||
color: var(--text);
|
||||
letter-spacing: -0.01em;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
b, strong {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Code & pre font */
|
||||
@@ -92,8 +112,8 @@ pre, code, kbd, samp {
|
||||
|
||||
/* Scrollbar clean styling */
|
||||
::-webkit-scrollbar {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
@@ -107,8 +127,13 @@ pre, code, kbd, samp {
|
||||
|
||||
/* Interactive focus */
|
||||
button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {
|
||||
outline: 1px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: var(--accent-soft);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* Hide floating dev badges */
|
||||
|
||||
+5
-5
@@ -1,20 +1,20 @@
|
||||
import { ToastProvider } from '@/components/ui/Toast';
|
||||
import type { Metadata } from 'next';
|
||||
import './globals.css';
|
||||
import { ToastProvider } from '@/components/ui/Toast';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'DataStack - Realtime Data Collection Platform',
|
||||
description: 'Self-hosted universal realtime data collection engine with Socket.IO ingestion, Redis buffer, JWT client auth, CSV batch rotation, and /vcon/ admin panel.',
|
||||
description: 'A self-hosted workspace for collecting, reviewing, and exporting realtime data.',
|
||||
manifest: '/manifest.json',
|
||||
openGraph: {
|
||||
title: 'DataStack - Realtime Data Collection Platform',
|
||||
description: 'Self-hosted universal realtime data collection engine with Socket.IO ingestion, Redis buffer, and CSV batch storage.',
|
||||
description: 'Collect, review, and export realtime data from one clear workspace.',
|
||||
type: 'website',
|
||||
},
|
||||
twitter: {
|
||||
card: 'summary_large_image',
|
||||
title: 'DataStack - Realtime Data Collection Platform',
|
||||
description: 'Self-hosted universal realtime data collection engine with Socket.IO ingestion.',
|
||||
description: 'A clear workspace for collecting, reviewing, and exporting realtime data.',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,7 +23,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
||||
<html lang="en" className="dark">
|
||||
<head>
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<meta name="theme-color" content="#2563eb" />
|
||||
<meta name="theme-color" content="#0a0a0b" />
|
||||
</head>
|
||||
<body suppressHydrationWarning className="min-h-screen bg-[var(--bg-main)] text-[var(--text)] antialiased">
|
||||
<ToastProvider>{children}</ToastProvider>
|
||||
|
||||
+1
-7
@@ -1,7 +1,6 @@
|
||||
import React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { MainLayout } from '@/components/layout/MainLayout';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
@@ -17,11 +16,6 @@ export default function NotFound() {
|
||||
Return Home
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/vcon/dashboard">
|
||||
<Button variant="primary" size="sm">
|
||||
Admin Console
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</MainLayout>
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import React from 'react';
|
||||
import { MainLayout } from '@/components/layout/MainLayout';
|
||||
import { Hero } from '@/components/sections/Hero';
|
||||
import { Features } from '@/components/sections/Features';
|
||||
import { Architecture } from '@/components/sections/Architecture';
|
||||
|
||||
export default function RootHomePage() {
|
||||
return (
|
||||
<MainLayout>
|
||||
<div className="flex flex-col gap-4">
|
||||
<Hero />
|
||||
<Architecture />
|
||||
<Features />
|
||||
</div>
|
||||
</MainLayout>
|
||||
);
|
||||
}
|
||||
+81
-368
@@ -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
@@ -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
@@ -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
@@ -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/{clientId}/{YYYY-MM-DD}.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
@@ -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>;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { AdminLogin } from '@/components/sections/AdminLogin';
|
||||
|
||||
export default function LoginPage() {
|
||||
return <AdminLogin />;
|
||||
}
|
||||
@@ -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
@@ -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 />;
|
||||
}
|
||||
@@ -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
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user