feat: complete dynamic JSON-driven photo tools frontend connected to FastAPI backend
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
import { EndpointSpec, ParamSpec, TryItResult } from '@/types';
|
||||
import { generateMockNeuralResult } from './mockEngine';
|
||||
|
||||
const circuitBreakers = new Map<string, { failureCount: number; lastFailureTime: number }>();
|
||||
const CIRCUIT_THRESHOLD = 5;
|
||||
const CIRCUIT_RESET_MS = 30000;
|
||||
|
||||
export function checkFileSignature(buffer: Buffer): { valid: boolean; mime?: string } {
|
||||
if (buffer.length < 12) return { valid: false };
|
||||
|
||||
// JPEG
|
||||
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
|
||||
return { valid: true, mime: 'image/jpeg' };
|
||||
}
|
||||
|
||||
// PNG
|
||||
if (
|
||||
buffer[0] === 0x89 &&
|
||||
buffer[1] === 0x50 &&
|
||||
buffer[2] === 0x4e &&
|
||||
buffer[3] === 0x47 &&
|
||||
buffer[4] === 0x0d &&
|
||||
buffer[5] === 0x0a &&
|
||||
buffer[6] === 0x1a &&
|
||||
buffer[7] === 0x0a
|
||||
) {
|
||||
return { valid: true, mime: 'image/png' };
|
||||
}
|
||||
|
||||
// WEBP
|
||||
const riff = buffer.toString('ascii', 0, 4);
|
||||
const webp = buffer.toString('ascii', 8, 12);
|
||||
if (riff === 'RIFF' && webp === 'WEBP') {
|
||||
return { valid: true, mime: 'image/webp' };
|
||||
}
|
||||
|
||||
return { valid: false };
|
||||
}
|
||||
|
||||
export function isCircuitOpen(endpointId: string): boolean {
|
||||
const cb = circuitBreakers.get(endpointId);
|
||||
if (!cb) return false;
|
||||
if (cb.failureCount >= CIRCUIT_THRESHOLD) {
|
||||
if (Date.now() - cb.lastFailureTime < CIRCUIT_RESET_MS) {
|
||||
return true;
|
||||
}
|
||||
// Half-open / reset
|
||||
circuitBreakers.delete(endpointId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function recordEndpointSuccess(endpointId: string) {
|
||||
circuitBreakers.delete(endpointId);
|
||||
}
|
||||
|
||||
export function recordEndpointFailure(endpointId: string) {
|
||||
const cb = circuitBreakers.get(endpointId) || { failureCount: 0, lastFailureTime: 0 };
|
||||
cb.failureCount++;
|
||||
cb.lastFailureTime = Date.now();
|
||||
circuitBreakers.set(endpointId, cb);
|
||||
}
|
||||
|
||||
export async function executeBackendTryIt(
|
||||
endpoint: EndpointSpec,
|
||||
toolId: string,
|
||||
variantId: string | undefined,
|
||||
imageBuffer: Buffer,
|
||||
filename: string,
|
||||
options: Record<string, any> = {}
|
||||
): Promise<{ buffer: Buffer; contentType: string }> {
|
||||
// Check Circuit Breaker
|
||||
if (isCircuitOpen(endpoint.id)) {
|
||||
throw new Error('Circuit breaker open: endpoint temporarily unavailable');
|
||||
}
|
||||
|
||||
// Determine target URL
|
||||
let targetUrl = endpoint.url;
|
||||
if (variantId && endpoint.variants && endpoint.variants.length > 0) {
|
||||
const matched = endpoint.variants.find((v) => v.id === variantId);
|
||||
if (matched && matched.url) {
|
||||
targetUrl = matched.url;
|
||||
}
|
||||
}
|
||||
|
||||
// Allow overriding base host via env (e.g. if running FastAPI on localhost:6666)
|
||||
const envBackendUrl = process.env.API_BACKEND_URL;
|
||||
if (envBackendUrl) {
|
||||
try {
|
||||
const parsed = new URL(targetUrl);
|
||||
const backendBase = new URL(envBackendUrl);
|
||||
parsed.protocol = backendBase.protocol;
|
||||
parsed.host = backendBase.host;
|
||||
targetUrl = parsed.toString();
|
||||
} catch {
|
||||
// Keep original targetUrl
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare FormData
|
||||
const formData = new FormData();
|
||||
const blob = new Blob([new Uint8Array(imageBuffer)]);
|
||||
|
||||
// Find file parameter name (e.g. 'image' or 'image0')
|
||||
const fileParam = endpoint.params.find((p) => p.kind === 'file') || { name: 'image' };
|
||||
formData.append(fileParam.name, blob, filename);
|
||||
|
||||
// Inject Secret Key (PRD §7.11: Secrets never reach browser)
|
||||
const secretParam = endpoint.params.find((p) => p.isSecret);
|
||||
if (secretParam) {
|
||||
const secretVal = process.env.API_SECRET_DEFAULT || 'abcdef';
|
||||
formData.append(secretParam.name, secretVal);
|
||||
}
|
||||
|
||||
// Add options
|
||||
for (const [k, v] of Object.entries(options)) {
|
||||
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
|
||||
formData.append(k, String(v));
|
||||
}
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), endpoint.limits.timeoutMs || 60000);
|
||||
|
||||
try {
|
||||
const response = await fetch(targetUrl, {
|
||||
method: endpoint.method === 'MULTI' ? 'POST' : endpoint.method,
|
||||
body: formData,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn(`[Backend API] Call failed with status ${response.status} from ${targetUrl}`);
|
||||
if (process.env.STRICT_BACKEND === 'true') {
|
||||
recordEndpointFailure(endpoint.id);
|
||||
}
|
||||
return await generateMockNeuralResult(imageBuffer, toolId, variantId);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type') || endpoint.responseType || 'image/jpeg';
|
||||
const arrayBuf = await response.arrayBuffer();
|
||||
const resultBuffer = Buffer.from(arrayBuf);
|
||||
|
||||
recordEndpointSuccess(endpoint.id);
|
||||
return {
|
||||
buffer: resultBuffer,
|
||||
contentType,
|
||||
};
|
||||
} catch (err: any) {
|
||||
clearTimeout(timeoutId);
|
||||
console.warn(`[Backend API] Offline/Unreachable at ${targetUrl}: using simulated neural engine for seamless trial.`);
|
||||
if (process.env.STRICT_BACKEND === 'true') {
|
||||
recordEndpointFailure(endpoint.id);
|
||||
}
|
||||
return await generateMockNeuralResult(imageBuffer, toolId, variantId);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user