- Add TelemetryTracker to record request fallback journeys, tracking step-by-step cascades across tiers, candidate error codes, cooldowns, and next actions - Add LiveWatcher for RAM-only interactive request inspection with 250-item FIFO safety cap and automatic memory flush on toggle off - Add REST and SSE streaming endpoints for real-time telemetry and live request logs - Upgrade Admin Telemetry tab with visual fallback breadcrumbs and live key health matrix - Add dedicated Live Logs tab with deep multi-tab inspector (Input, Output, Metadata, Debug), search, filters, and JSON export - Add unit and integration tests (test-live-watcher.ts, test-telemetry-fallback.ts)
274 lines
10 KiB
TypeScript
274 lines
10 KiB
TypeScript
import http from 'http';
|
|
import assert from 'assert';
|
|
import app from './src/index';
|
|
import { telemetryTracker, RequestFallbackJourney, FallbackStep } from './src/telemetryTracker';
|
|
import { liveWatcher } from './src/liveWatcher';
|
|
import { configStore } from './src/configStore';
|
|
|
|
const PORT = 3998;
|
|
const API_KEY = 'test_password';
|
|
|
|
console.log('🧪 Starting Telemetry Fallback & Admin HTTP API Test Suite...\n');
|
|
|
|
async function runTests() {
|
|
// 0. Start a mock upstream server
|
|
const mockUpstream = http.createServer((req, res) => {
|
|
let body = '';
|
|
req.on('data', chunk => (body += chunk));
|
|
req.on('end', () => {
|
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
res.end(
|
|
JSON.stringify({
|
|
id: 'chatcmpl-mock-123',
|
|
object: 'chat.completion',
|
|
created: Math.floor(Date.now() / 1000),
|
|
model: 'mock-model-v1',
|
|
choices: [
|
|
{
|
|
index: 0,
|
|
message: { role: 'assistant', content: 'Telemetry & live logs verification response.' },
|
|
finish_reason: 'stop'
|
|
}
|
|
],
|
|
usage: { prompt_tokens: 15, completion_tokens: 10, total_tokens: 25 }
|
|
})
|
|
);
|
|
});
|
|
});
|
|
await new Promise<void>((resolve) => mockUpstream.listen(0, resolve));
|
|
const upstreamPort = (mockUpstream.address() as any).port;
|
|
const upstreamBaseUrl = `http://localhost:${upstreamPort}`;
|
|
|
|
const server = http.createServer(app);
|
|
await new Promise<void>((resolve) => server.listen(PORT, resolve));
|
|
|
|
try {
|
|
// 1. Unit Test: Fallback Journey Tracking in telemetryTracker
|
|
console.log('1. Testing TelemetryTracker fallback journey tracking...');
|
|
|
|
const sampleHops: FallbackStep[] = [
|
|
{
|
|
stepIndex: 1,
|
|
timestamp: new Date().toISOString(),
|
|
tierIndex: 0,
|
|
tierName: 'Main Tier (Flash)',
|
|
providerId: 'prov-gemini',
|
|
providerName: 'Google AI Studio',
|
|
providerType: 'gemini',
|
|
model: 'gemini-1.5-flash',
|
|
keyIndex: 0,
|
|
maskedKey: 'AIzaSy...4X9',
|
|
durationMs: 120,
|
|
status: 'rate_limited',
|
|
statusCode: 429,
|
|
errorMessage: 'Resource has been exhausted (e.g. check quota).',
|
|
rateLimitedUntil: Date.now() + 60000,
|
|
cooldownSeconds: 60,
|
|
nextAction: 'Rotating to next key in Tier 0'
|
|
},
|
|
{
|
|
stepIndex: 2,
|
|
timestamp: new Date().toISOString(),
|
|
tierIndex: 0,
|
|
tierName: 'Main Tier (Flash)',
|
|
providerId: 'prov-gemini',
|
|
providerName: 'Google AI Studio',
|
|
providerType: 'gemini',
|
|
model: 'gemini-1.5-flash',
|
|
keyIndex: 1,
|
|
maskedKey: 'AIzaSy...8B2',
|
|
durationMs: 95,
|
|
status: 'server_error',
|
|
statusCode: 503,
|
|
errorMessage: 'The model is overloaded. Please try again later.',
|
|
rateLimitedUntil: Date.now() + 15000,
|
|
cooldownSeconds: 15,
|
|
nextAction: 'Tier 0 exhausted. Cascading to Fallback Tier 1'
|
|
},
|
|
{
|
|
stepIndex: 3,
|
|
timestamp: new Date().toISOString(),
|
|
tierIndex: 1,
|
|
tierName: 'Backup Tier (Groq)',
|
|
providerId: 'prov-groq',
|
|
providerName: 'Groq Cloud',
|
|
providerType: 'groq',
|
|
model: 'llama-3.3-70b-versatile',
|
|
keyIndex: 0,
|
|
maskedKey: 'gsk_...11a',
|
|
durationMs: 215,
|
|
status: 'success',
|
|
statusCode: 200,
|
|
nextAction: 'Served successfully'
|
|
}
|
|
];
|
|
|
|
const sampleJourney: RequestFallbackJourney = {
|
|
requestId: 'req_fallback_trace_001',
|
|
timestamp: new Date().toISOString(),
|
|
requestedModel: 'smart-pipeline',
|
|
resolvedModelName: 'smart-pipeline',
|
|
resolvedModelId: 'model-smart-01',
|
|
finalStatus: 'success_fallback',
|
|
totalDurationMs: 430,
|
|
totalHops: 3,
|
|
fallbackOccurred: true,
|
|
finalServedBy: {
|
|
tierIndex: 1,
|
|
tierName: 'Backup Tier (Groq)',
|
|
providerName: 'Groq Cloud',
|
|
providerType: 'groq',
|
|
model: 'llama-3.3-70b-versatile',
|
|
maskedKey: 'gsk_...11a'
|
|
},
|
|
tokens: {
|
|
promptTokens: 45,
|
|
completionTokens: 30,
|
|
totalTokens: 75
|
|
},
|
|
steps: sampleHops
|
|
};
|
|
|
|
telemetryTracker.recordJourney(sampleJourney);
|
|
|
|
const recent = telemetryTracker.getRecentJourneys();
|
|
assert.strictEqual(recent.length >= 1, true);
|
|
const recorded = recent.find(j => j.requestId === 'req_fallback_trace_001');
|
|
assert.ok(recorded, 'Recorded journey must exist');
|
|
assert.strictEqual(recorded.finalStatus, 'success_fallback');
|
|
assert.strictEqual(recorded.totalHops, 3);
|
|
assert.strictEqual(recorded.fallbackOccurred, true);
|
|
assert.strictEqual(recorded.steps.length, 3);
|
|
assert.strictEqual(recorded.steps[0].status, 'rate_limited');
|
|
assert.strictEqual(recorded.steps[0].cooldownSeconds, 60);
|
|
assert.strictEqual(recorded.steps[1].status, 'server_error');
|
|
assert.strictEqual(recorded.steps[2].status, 'success');
|
|
console.log(' ✓ Fallback journey successfully captures multi-tier failures, cooldowns, and next action.');
|
|
|
|
// 2. HTTP Admin Endpoints: Telemetry Traces
|
|
console.log('\n2. Testing GET /api/admin/telemetry/fallback-traces...');
|
|
const telRes = await fetch(`http://localhost:${PORT}/api/admin/telemetry/fallback-traces`, {
|
|
headers: { 'Authorization': `Bearer ${API_KEY}` }
|
|
});
|
|
assert.strictEqual(telRes.status, 200);
|
|
const telData = await telRes.json() as any;
|
|
assert.ok(Array.isArray(telData.journeys));
|
|
assert.ok(Array.isArray(telData.keys));
|
|
assert.strictEqual(telData.journeys.some((j: any) => j.requestId === 'req_fallback_trace_001'), true);
|
|
console.log(' ✓ GET /api/admin/telemetry/fallback-traces returned journeys and keys successfully.');
|
|
|
|
// 3. HTTP Admin Endpoints: Live Logs State & Toggle
|
|
console.log('\n3. Testing GET /api/admin/live-logs/state...');
|
|
const stateRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/state`, {
|
|
headers: { 'Authorization': `Bearer ${API_KEY}` }
|
|
});
|
|
assert.strictEqual(stateRes.status, 200);
|
|
const stateData = await stateRes.json() as any;
|
|
assert.strictEqual(typeof stateData.active, 'boolean');
|
|
assert.strictEqual(stateData.maxCapacity, 250);
|
|
console.log(' ✓ Initial live logs state verified.');
|
|
|
|
console.log('\n4. Testing POST /api/admin/live-logs/toggle (ON)...');
|
|
const toggleOnRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/toggle`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${API_KEY}`
|
|
},
|
|
body: JSON.stringify({ enabled: true })
|
|
});
|
|
assert.strictEqual(toggleOnRes.status, 200);
|
|
const toggleOnData = await toggleOnRes.json() as any;
|
|
assert.strictEqual(toggleOnData.active, true);
|
|
assert.strictEqual(liveWatcher.isActive(), true);
|
|
console.log(' ✓ Watcher successfully toggled ON via Admin API.');
|
|
|
|
// 5. Send an actual Chat Completion request and verify Live Watcher captures it
|
|
console.log('\n5. Sending API completion request and verifying RAM capture in Live Watcher...');
|
|
const uniqueModelName = `test-telemetry-model-${Date.now()}`;
|
|
const testProv = configStore.saveProvider({
|
|
name: 'Test Upstream Provider',
|
|
type: 'custom',
|
|
baseUrl: upstreamBaseUrl,
|
|
keys: ['mock-api-key-1']
|
|
});
|
|
|
|
const testModel = configStore.saveCustomModel({
|
|
name: uniqueModelName,
|
|
tiers: [
|
|
{
|
|
tierIndex: 0,
|
|
name: 'Main Tier',
|
|
targets: [{ providerId: testProv.id, model: 'mock-model-v1' }]
|
|
}
|
|
]
|
|
});
|
|
|
|
const completionRes = await fetch(`http://localhost:${PORT}/v1/chat/completions`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${API_KEY}`
|
|
},
|
|
body: JSON.stringify({
|
|
model: uniqueModelName,
|
|
messages: [{ role: 'user', content: 'Verify live watcher inspection' }]
|
|
})
|
|
});
|
|
assert.strictEqual(completionRes.status, 200);
|
|
|
|
// Now check GET /api/admin/live-logs/entries
|
|
const entriesRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/entries`, {
|
|
headers: { 'Authorization': `Bearer ${API_KEY}` }
|
|
});
|
|
assert.strictEqual(entriesRes.status, 200);
|
|
const entriesData = await entriesRes.json() as any;
|
|
assert.strictEqual(entriesData.state.active, true);
|
|
assert.strictEqual(entriesData.entries.length >= 1, true);
|
|
|
|
const captured = entriesData.entries[0];
|
|
assert.strictEqual(captured.input.messages[0].content, 'Verify live watcher inspection');
|
|
assert.strictEqual(captured.output.completionText, 'Telemetry & live logs verification response.');
|
|
assert.strictEqual(captured.output.tokens.totalTokens, 25);
|
|
assert.strictEqual(captured.debug.stepTraces.length >= 1, true);
|
|
assert.strictEqual(captured.debug.stepTraces[0].status, 'success');
|
|
console.log(' ✓ Incoming API request, output, tokens, metadata, and candidate trace successfully inspected from RAM.');
|
|
|
|
// 6. Test Toggling OFF flushes all RAM data
|
|
console.log('\n6. Testing POST /api/admin/live-logs/toggle (OFF) flushes RAM data...');
|
|
const toggleOffRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/toggle`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${API_KEY}`
|
|
},
|
|
body: JSON.stringify({ enabled: false })
|
|
});
|
|
assert.strictEqual(toggleOffRes.status, 200);
|
|
const toggleOffData = await toggleOffRes.json() as any;
|
|
assert.strictEqual(toggleOffData.active, false);
|
|
assert.strictEqual(toggleOffData.bufferCount, 0);
|
|
|
|
const checkFlushRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/entries`, {
|
|
headers: { 'Authorization': `Bearer ${API_KEY}` }
|
|
});
|
|
const checkFlushData = await checkFlushRes.json() as any;
|
|
assert.strictEqual(checkFlushData.entries.length, 0, 'Buffer entries must be empty after toggle off');
|
|
console.log(' ✓ Toggling OFF completely purged all logs from memory.');
|
|
|
|
// Cleanup test models
|
|
configStore.deleteCustomModel(testModel.id);
|
|
configStore.deleteProvider(testProv.id);
|
|
|
|
console.log('\n🎉 ALL TELEMETRY FALLBACK & ADMIN HTTP API TESTS PASSED!\n');
|
|
|
|
} finally {
|
|
server.close();
|
|
mockUpstream.close();
|
|
}
|
|
}
|
|
|
|
runTests().catch((err) => {
|
|
console.error('Test failed with error:', err);
|
|
process.exit(1);
|
|
});
|