248 lines
11 KiB
TypeScript
248 lines
11 KiB
TypeScript
import http from 'http';
|
|
import assert from 'assert';
|
|
import app from './src/index';
|
|
import { config } from './src/config';
|
|
import { configStore } from './src/configStore';
|
|
import { modelCircuitBreaker } from './src/modelCircuitBreaker';
|
|
import { revolverEngine, GEMINI_SAFETY_SETTINGS_BLOCK_NONE } from './src/revolverEngine';
|
|
import { HarmBlockThreshold } from '@google/generative-ai';
|
|
|
|
const PORT = 3998;
|
|
const API_KEY = 'test_password';
|
|
|
|
console.log('🧪 Starting Moderation Settings & Emergency Cooldown Recovery Test Suite...\n');
|
|
|
|
async function runTests() {
|
|
config.candidateTimeoutMs = 500;
|
|
config.streamFirstTokenTimeoutMs = 400;
|
|
config.modelCooldownDurationMs = 2000;
|
|
config.rateLimitDurationMs = 2000;
|
|
|
|
// =========================================================================
|
|
// TEST 1: Gemini Content Moderation Injection & Configuration
|
|
// =========================================================================
|
|
console.log('1. Testing Gemini Content Moderation Injection & Config...');
|
|
assert.strictEqual(config.disableGeminiModeration, true, 'Default disableGeminiModeration must be true');
|
|
|
|
// Verify all 4 API-supported categories exist with BLOCK_NONE
|
|
assert.strictEqual(GEMINI_SAFETY_SETTINGS_BLOCK_NONE.length, 4);
|
|
const categories = GEMINI_SAFETY_SETTINGS_BLOCK_NONE.map(s => s.category);
|
|
assert.ok(categories.includes('HARM_CATEGORY_HARASSMENT' as any));
|
|
assert.ok(categories.includes('HARM_CATEGORY_HATE_SPEECH' as any));
|
|
assert.ok(categories.includes('HARM_CATEGORY_SEXUALLY_EXPLICIT' as any));
|
|
assert.ok(categories.includes('HARM_CATEGORY_DANGEROUS_CONTENT' as any));
|
|
GEMINI_SAFETY_SETTINGS_BLOCK_NONE.forEach(s => {
|
|
assert.strictEqual(s.threshold, HarmBlockThreshold.BLOCK_NONE);
|
|
});
|
|
|
|
// Verify ProviderConfig persistence with disableModeration
|
|
const testProvMod = configStore.saveProvider({
|
|
name: 'Gemini Moderation Test Provider',
|
|
type: 'gemini',
|
|
baseUrl: 'https://generativelanguage.googleapis.com',
|
|
keys: ['AIzaSyDummyTestKeyForModeration'],
|
|
disableModeration: true
|
|
});
|
|
assert.strictEqual(testProvMod.disableModeration, true);
|
|
configStore.deleteProvider(testProvMod.id);
|
|
console.log(' ✓ Gemini content moderation settings, BLOCK_NONE injection, and provider flags verified.');
|
|
|
|
// =========================================================================
|
|
// Upstream Mock Server Setup
|
|
// =========================================================================
|
|
const candidateAttempts: string[] = [];
|
|
|
|
const mockServer = http.createServer((req, res) => {
|
|
let body = '';
|
|
req.on('data', chunk => (body += chunk));
|
|
req.on('end', () => {
|
|
const parsed = JSON.parse(body || '{}');
|
|
const authHeader = req.headers['authorization'] || '';
|
|
const key = authHeader.replace('Bearer ', '');
|
|
const model = parsed.model;
|
|
const attemptTag = `${model}:${key}`;
|
|
candidateAttempts.push(attemptTag);
|
|
|
|
if (attemptTag === 'mock-t0-model:key-t0-1') {
|
|
// Candidate 1 fails with 503
|
|
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
res.end(JSON.stringify({ error: { message: '[503 Service Unavailable] Model overloaded' } }));
|
|
} else if (attemptTag === 'mock-t0-model:key-t0-2') {
|
|
// Candidate 2 fails with 503
|
|
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
res.end(JSON.stringify({ error: { message: '[503 Service Unavailable] Model overloaded' } }));
|
|
} else if (attemptTag === 'mock-t1-model:key-t1-1') {
|
|
// Candidate 3 in Tier 1 succeeds!
|
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
res.end(JSON.stringify({
|
|
id: 'chatcmpl-emergency-success',
|
|
object: 'chat.completion',
|
|
created: Math.floor(Date.now() / 1000),
|
|
model: 'mock-t1-model',
|
|
choices: [{ message: { role: 'assistant', content: 'Emergency probe saved the request!' } }],
|
|
usage: { prompt_tokens: 10, completion_tokens: 15, total_tokens: 25 }
|
|
}));
|
|
} else if (model === 'all-fail-model') {
|
|
// All fail
|
|
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
res.end(JSON.stringify({ error: { message: 'Outage continues' } }));
|
|
} else {
|
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
res.end(JSON.stringify({
|
|
choices: [{ message: { role: 'assistant', content: 'Default OK' } }]
|
|
}));
|
|
}
|
|
});
|
|
});
|
|
|
|
await new Promise<void>(resolve => mockServer.listen(0, resolve));
|
|
const upstreamPort = (mockServer.address() as any).port;
|
|
const upstreamBaseUrl = `http://localhost:${upstreamPort}`;
|
|
|
|
// Start GeminiRevolver server
|
|
const server = app.listen(PORT);
|
|
await new Promise<void>(resolve => server.once('listening', resolve));
|
|
const baseUrl = `http://localhost:${PORT}`;
|
|
|
|
try {
|
|
// =========================================================================
|
|
// TEST 2: All Tiers & Key-Model Pairs on Cooldown -> Sequential Probe Recovery
|
|
// =========================================================================
|
|
console.log('\n2. Testing sequential probe recovery when ALL tiers and key-model pairs are on cooldown...');
|
|
|
|
const pT0 = configStore.saveProvider({
|
|
name: 'Emergency Provider Tier 0',
|
|
type: 'custom',
|
|
baseUrl: upstreamBaseUrl,
|
|
keys: ['key-t0-1', 'key-t0-2', 'key-t0-3', 'key-t0-4', 'key-t0-5']
|
|
});
|
|
|
|
const pT1 = configStore.saveProvider({
|
|
name: 'Emergency Provider Tier 1',
|
|
type: 'custom',
|
|
baseUrl: upstreamBaseUrl,
|
|
keys: ['key-t1-1']
|
|
});
|
|
|
|
const customModelName = `emergency-recovery-model-${Date.now()}`;
|
|
const testModel = configStore.saveCustomModel({
|
|
name: customModelName,
|
|
tiers: [
|
|
{
|
|
tierIndex: 0,
|
|
name: 'Tier 0',
|
|
targets: [{ providerId: pT0.id, model: 'mock-t0-model' }]
|
|
},
|
|
{
|
|
tierIndex: 1,
|
|
name: 'Tier 1',
|
|
targets: [{ providerId: pT1.id, model: 'mock-t1-model' }]
|
|
}
|
|
]
|
|
});
|
|
|
|
// Explicitly place ALL targets on circuit breaker cooldown
|
|
modelCircuitBreaker.tripCooldown(pT0.id, 'mock-t0-model', 'Simulated 503 outage');
|
|
modelCircuitBreaker.tripCooldown(pT1.id, 'mock-t1-model', 'Simulated 503 outage');
|
|
|
|
// Also mark keys rate-limited
|
|
for (const k of pT0.keys) {
|
|
configStore.updateKeyStats(pT0.id, k.key, { rateLimitedUntil: Date.now() + 60000 });
|
|
}
|
|
configStore.updateKeyStats(pT1.id, 'key-t1-1', { rateLimitedUntil: Date.now() + 60000 });
|
|
|
|
// Verify all key-model pairs are detected as on cooldown
|
|
const areAllOnCooldown = revolverEngine.areAllKeyModelPairsOnCooldown(testModel);
|
|
assert.strictEqual(areAllOnCooldown, true, 'areAllKeyModelPairsOnCooldown must return true when everything is in cooldown');
|
|
|
|
candidateAttempts.length = 0;
|
|
|
|
// Send request while ALL key-model pairs are in cooldown
|
|
const response = await fetch(`${baseUrl}/v1/chat/completions`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${API_KEY}`
|
|
},
|
|
body: JSON.stringify({
|
|
model: customModelName,
|
|
messages: [{ role: 'user', content: 'Emergency probe test' }],
|
|
stream: false
|
|
})
|
|
});
|
|
|
|
assert.strictEqual(response.status, 200, `Expected 200 OK after emergency sequential recovery, got ${response.status}`);
|
|
const data = (await response.json()) as any;
|
|
assert.strictEqual(data.choices[0].message.content, 'Emergency probe saved the request!');
|
|
|
|
// Verify candidates were attempted sequentially, skipping keys 3..5 after 2nd 503: Candidate 1 -> Candidate 2 -> Candidate 3 (Tier 1)
|
|
assert.strictEqual(candidateAttempts.length, 3, 'Should only try 2 keys on Tier 0 before skipping remaining 3 keys and failing over to Tier 1');
|
|
assert.strictEqual(candidateAttempts[0], 'mock-t0-model:key-t0-1', 'Candidate 1 must be attempted first with revoked cooldown');
|
|
assert.strictEqual(candidateAttempts[1], 'mock-t0-model:key-t0-2', 'Candidate 2 (1 retry key) must be attempted next with revoked cooldown');
|
|
assert.strictEqual(candidateAttempts[2], 'mock-t1-model:key-t1-1', 'Candidate 3 in Tier 1 must be attempted next (skipping keys 3..5 of Tier 0) and succeed');
|
|
|
|
// Verify Candidate 1 and Candidate 2 were put back on cooldown upon failure
|
|
assert.strictEqual(modelCircuitBreaker.isTargetInCooldown(pT0.id, 'mock-t0-model'), true, 'Tier 0 target must be back in cooldown after failing');
|
|
|
|
// Verify Candidate 3 is now healthy
|
|
assert.strictEqual(modelCircuitBreaker.isTargetAvailable(pT1.id, 'mock-t1-model'), true, 'Tier 1 target must be healthy after successful probe');
|
|
console.log(' ✓ Emergency sequential recovery cleanly revoked Candidate 1, failed & put back on cooldown, failed Candidate 2 & put back on cooldown, and succeeded on Candidate 3.');
|
|
|
|
// =========================================================================
|
|
// TEST 3: All Tiers & Key-Model Pairs on Cooldown -> All Fail -> Graceful 503
|
|
// =========================================================================
|
|
console.log('\n3. Testing emergency recovery when ALL candidates error out...');
|
|
|
|
const allFailModelName = `all-fail-model-${Date.now()}`;
|
|
const allFailModel = configStore.saveCustomModel({
|
|
name: allFailModelName,
|
|
tiers: [
|
|
{
|
|
tierIndex: 0,
|
|
name: 'Tier 0',
|
|
targets: [{ providerId: pT0.id, model: 'all-fail-model' }]
|
|
}
|
|
]
|
|
});
|
|
|
|
modelCircuitBreaker.tripCooldown(pT0.id, 'all-fail-model', 'Outage');
|
|
configStore.updateKeyStats(pT0.id, 'key-t0-1', { rateLimitedUntil: Date.now() + 60000 });
|
|
configStore.updateKeyStats(pT0.id, 'key-t0-2', { rateLimitedUntil: Date.now() + 60000 });
|
|
|
|
const allFailRes = await fetch(`${baseUrl}/v1/chat/completions`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${API_KEY}`
|
|
},
|
|
body: JSON.stringify({
|
|
model: allFailModelName,
|
|
messages: [{ role: 'user', content: 'All fail test' }],
|
|
stream: false
|
|
})
|
|
});
|
|
|
|
assert.strictEqual(allFailRes.status, 503, 'Expected 503 all_tiers_exhausted when all probes fail');
|
|
const allFailData = (await allFailRes.json()) as any;
|
|
assert.strictEqual(allFailData.error.code, 'all_tiers_exhausted');
|
|
assert.strictEqual(modelCircuitBreaker.isTargetInCooldown(pT0.id, 'all-fail-model'), true);
|
|
console.log(' ✓ When all emergency candidate probes fail, request gracefully terminated with 503 all_tiers_exhausted and all were put back on cooldown.');
|
|
|
|
// Cleanup
|
|
configStore.deleteCustomModel(testModel.id);
|
|
configStore.deleteCustomModel(allFailModel.id);
|
|
configStore.deleteProvider(pT0.id);
|
|
configStore.deleteProvider(pT1.id);
|
|
modelCircuitBreaker.reset();
|
|
|
|
console.log('\n🎉 ALL MODERATION & EMERGENCY COOLDOWN RECOVERY TESTS PASSED SUCCESSFULLY!\n');
|
|
} finally {
|
|
server.close();
|
|
mockServer.close();
|
|
}
|
|
}
|
|
|
|
runTests().catch(err => {
|
|
console.error('Test failed with error:', err);
|
|
process.exit(1);
|
|
});
|