Spaces:
Sleeping
Sleeping
Pixel Pinch Extensions
debug: add startup trace logs to identify module import hang on HF Spaces
fc5c6d4 Download src/bun-server.js from sacred-eye/pixelpinch-proxy: direct link, hf CLI and curl.
- Browser
- Download file 36.5 kB
-
https://huggingface.co/spaces/sacred-eye/pixelpinch-proxy/resolve/main/src/bun-server.js
- Command line
-
hf download hf://spaces/sacred-eye/pixelpinch-proxy/src/bun-server.js
-
curl -L -o bun-server.js https://huggingface.co/spaces/sacred-eye/pixelpinch-proxy/resolve/main/src/bun-server.js
36.5 kB
| // ============================================ | |
| // PIXELPINCH - BUN NATIVE SERVER | |
| // OPTIMIZED FOR HUGGING FACE FREE TIER | |
| // MAXIMUM COMPRESSION EDITION | |
| // ============================================ | |
| console.error('[BOOT] Starting imports...'); | |
| import 'dotenv/config'; | |
| console.error('[BOOT] dotenv loaded'); | |
| import './polyfills.js'; | |
| console.error('[BOOT] polyfills loaded'); | |
| import CONFIG from './config.js'; | |
| console.error('[BOOT] config loaded'); | |
| import logger, { requestLogger, compressionLogger, cacheLogger, securityLogger } from './logger.js'; | |
| console.error('[BOOT] logger loaded'); | |
| import { fetchImage, isValidImageUrl, safeDecodeURI } from './fetch.js'; | |
| console.error('[BOOT] fetch loaded'); | |
| import { compressImage, parseParams, calculateAdaptiveQuality, formatBytes } from './compress.js'; | |
| console.error('[BOOT] compress loaded'); | |
| import { cacheWrapper } from './cache.js'; | |
| console.error('[BOOT] cache loaded'); | |
| import { optimizeForBun } from './bun-optimizations.js'; | |
| console.error('[BOOT] bun-optimizations loaded'); | |
| import performanceMonitor from './performance-monitor.js'; | |
| console.error('[BOOT] All imports complete'); | |
| // Enable Bun optimizations | |
| if (optimizeForBun()) { | |
| logger.debug('Bun optimizations enabled'); | |
| } | |
| // ============================================ | |
| // RATE LIMITER IMPLEMENTATION | |
| // ============================================ | |
| const rateLimiter = { | |
| hits: new Map(), | |
| windowMs: CONFIG.RATE_LIMIT_WINDOW_MS, | |
| max: CONFIG.RATE_LIMIT_MAX_REQUESTS, | |
| check(ip) { | |
| const now = Date.now(); | |
| const windowStart = now - this.windowMs; | |
| let requestTimestamps = this.hits.get(ip) || []; | |
| // Filter out old requests | |
| requestTimestamps = requestTimestamps.filter(timestamp => timestamp > windowStart); | |
| if (requestTimestamps.length >= this.max) { | |
| return false; | |
| } | |
| requestTimestamps.push(now); | |
| this.hits.set(ip, requestTimestamps); | |
| return true; | |
| } | |
| }; | |
| // Periodic cleanup to avoid memory leak | |
| setInterval(() => { | |
| const windowStart = Date.now() - rateLimiter.windowMs; | |
| for (const [ip, timestamps] of rateLimiter.hits.entries()) { | |
| const validTimestamps = timestamps.filter(t => t > windowStart); | |
| if (validTimestamps.length === 0) { | |
| rateLimiter.hits.delete(ip); | |
| } else { | |
| rateLimiter.hits.set(ip, validTimestamps); | |
| } | |
| } | |
| }, 60000); // Cleanup every minute | |
| // ============================================ | |
| // STARTUP LOGGING | |
| // ============================================ | |
| logger.info('Starting PixelPinch Proxy (Native Bun)', { | |
| version: '2.1.0-enhanced', | |
| port: CONFIG.PORT, | |
| runtime: 'Bun', | |
| bun_version: Bun.version, | |
| platform: 'huggingface-free-tier' | |
| }); | |
| console.error(''); | |
| console.error('╔════════════════════════════════════════════════════╗'); | |
| console.error('║ PIXELPINCH - MAX COMPRESSION PROXY ║'); | |
| console.error('║ Hugging Face Free Edition ║'); | |
| console.error('║ (Native Bun Server) ║'); | |
| console.error('╠════════════════════════════════════════════════════╣'); | |
| console.error(`║ 🌐 Port: ${CONFIG.PORT} ║`); | |
| console.error(`║ 📊 Quality: ${CONFIG.MIN_QUALITY}-${CONFIG.MAX_QUALITY} (default: ${CONFIG.DEFAULT_QUALITY}) ║`); | |
| console.error(`║ 📐 Max Size: ${CONFIG.MAX_WIDTH}x${CONFIG.MAX_HEIGHT} ║`); | |
| console.error('╠════════════════════════════════════════════════════╣'); | |
| console.error('║ ✅ AVIF Support: ENABLED (Priority) ║'); | |
| console.error('║ ✅ WebP Support: ENABLED ║'); | |
| console.error('║ ✅ MozJPEG: ENABLED ║'); | |
| console.error('║ ✅ Adaptive Quality: ENABLED ║'); | |
| console.error('║ ✅ Maximum Compression: ENABLED ║'); | |
| console.error('║ ✅ Rate Limiting: ENABLED ║'); | |
| console.error('║ ✅ Caching: ENABLED ║'); | |
| console.error('║ ✅ Security Headers: ENABLED ║'); | |
| console.error('╚════════════════════════════════════════════════════╝'); | |
| console.error(''); | |
| // ============================================ | |
| // HELPERS | |
| // ============================================ | |
| function createErrorResponse(error, status = 500, details = {}) { | |
| const errorResponse = { | |
| error: true, | |
| status, | |
| message: error, | |
| timestamp: new Date().toISOString(), | |
| ...details | |
| }; | |
| return new Response(JSON.stringify(errorResponse), { | |
| status, | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| 'Cache-Control': 'no-cache, no-store, must-revalidate', | |
| 'X-Content-Type-Options': 'nosniff' | |
| } | |
| }); | |
| } | |
| function createRedirect(url, extraHeaders = new Headers()) { | |
| const headers = new Headers(extraHeaders); | |
| headers.set('Location', url); | |
| headers.set('X-Original-Size', '0'); | |
| headers.set('X-Bytes-Saved', '0'); | |
| headers.set('Cache-Control', 'private, no-cache'); | |
| return new Response(null, { status: 302, headers }); | |
| } | |
| function createCompressedResponse(data, format, originalSize, compressedSize, compressionMethod, extraHeaders = new Headers()) { | |
| const saved = originalSize - compressedSize; | |
| const ratio = ((saved / originalSize) * 100).toFixed(1); | |
| const headers = new Headers(extraHeaders); | |
| headers.set('Content-Type', `image/${format}`); | |
| headers.set('Content-Length', compressedSize.toString()); | |
| headers.set('X-Original-Size', originalSize.toString()); | |
| headers.set('X-Bytes-Saved', saved.toString()); | |
| headers.set('X-Compression-Ratio', `${ratio}%`); | |
| headers.set('X-Format', format); | |
| headers.set('X-Compression-Effort', format === 'avif' ? '9' : format === 'webp' ? '6' : 'max'); | |
| headers.set('X-Compression-Method', compressionMethod); | |
| headers.set('Cache-Control', 'public, max-age=31536000, immutable'); | |
| headers.set('X-Content-Type-Options', 'nosniff'); | |
| headers.set('Vary', 'Accept'); | |
| headers.set('X-Proxy', 'PixelPinch-Max-Compression'); | |
| return new Response(data, { status: 200, headers }); | |
| } | |
| function getCorsHeaders() { | |
| return { | |
| 'Access-Control-Allow-Origin': '*', | |
| 'Access-Control-Allow-Methods': 'GET, OPTIONS, HEAD', | |
| 'Access-Control-Allow-Headers': 'Content-Type, Accept, User-Agent', | |
| 'Access-Control-Max-Age': '86400', | |
| 'Access-Control-Expose-Headers': 'X-Original-Size, X-Bytes-Saved, X-Compression-Ratio, X-Format, X-Compression-Effort, X-Proxy' | |
| }; | |
| } | |
| function addCorsHeaders(headers) { | |
| const cors = getCorsHeaders(); | |
| for (const [key, value] of Object.entries(cors)) { | |
| headers.set(key, value); | |
| } | |
| } | |
| function addSecurityHeaders(headers) { | |
| headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload'); | |
| headers.set('X-Content-Type-Options', 'nosniff'); | |
| headers.set('Referrer-Policy', 'no-referrer'); | |
| } | |
| // ============================================ | |
| // REQUEST QUEUING SYSTEM | |
| // ============================================ | |
| class RequestQueue { | |
| constructor(maxConcurrent = 15, maxQueueSize = 50) { | |
| this.maxConcurrent = maxConcurrent; | |
| this.maxQueueSize = maxQueueSize; | |
| this.activeRequests = 0; | |
| this.queue = []; | |
| this.metrics = { | |
| totalRequests: 0, | |
| queuedRequests: 0, | |
| rejectedRequests: 0, | |
| avgQueueTime: 0, | |
| maxQueueTime: 0 | |
| }; | |
| } | |
| async execute(requestFn, priority = 'normal', timeoutMs = CONFIG.QUEUE_TIMEOUT_MS) { | |
| this.metrics.totalRequests++; | |
| // Check if we can execute immediately | |
| if (this.activeRequests < this.maxConcurrent) { | |
| return this._executeDirect(requestFn, timeoutMs); | |
| } | |
| // Check queue capacity | |
| if (this.queue.length >= this.maxQueueSize) { | |
| this.metrics.rejectedRequests++; | |
| throw new Error('Request queue full - server overloaded'); | |
| } | |
| // Add to queue based on priority | |
| return this._queueRequest(requestFn, priority, timeoutMs); | |
| } | |
| async _executeDirect(requestFn, timeoutMs) { | |
| this.activeRequests++; | |
| let timeoutId; | |
| try { | |
| // Add timeout to the request execution | |
| return await Promise.race([ | |
| requestFn(), | |
| new Promise((_, reject) => { | |
| timeoutId = setTimeout(() => reject(new Error('Request timeout')), timeoutMs); | |
| }) | |
| ]); | |
| } finally { | |
| if (timeoutId) clearTimeout(timeoutId); | |
| this.activeRequests--; | |
| this._processQueue(); | |
| } | |
| } | |
| async _queueRequest(requestFn, priority, timeoutMs) { | |
| this.metrics.queuedRequests++; | |
| const queueStart = Date.now(); | |
| return new Promise((resolve, reject) => { | |
| // Add a queue-wait timeout so requests don't hang indefinitely | |
| const queueTimeoutId = setTimeout(() => { | |
| // Remove this item from the queue if it's still there | |
| const idx = this.queue.indexOf(queueItem); | |
| if (idx !== -1) this.queue.splice(idx, 1); | |
| reject(new Error('Request timeout')); | |
| }, timeoutMs); | |
| const queueItem = { | |
| requestFn, | |
| priority, | |
| resolve: (val) => { clearTimeout(queueTimeoutId); resolve(val); }, | |
| reject: (err) => { clearTimeout(queueTimeoutId); reject(err); }, | |
| queueStart, | |
| timestamp: Date.now(), | |
| timeoutMs | |
| }; | |
| // Insert based on priority | |
| if (priority === 'high') { | |
| this.queue.unshift(queueItem); | |
| } else { | |
| this.queue.push(queueItem); | |
| } | |
| }); | |
| } | |
| _processQueue() { | |
| while (this.activeRequests < this.maxConcurrent && this.queue.length > 0) { | |
| const queueItem = this.queue.shift(); | |
| const queueTime = Date.now() - queueItem.queueStart; | |
| // Update metrics | |
| this.metrics.avgQueueTime = (this.metrics.avgQueueTime + queueTime) / 2; | |
| this.metrics.maxQueueTime = Math.max(this.metrics.maxQueueTime, queueTime); | |
| // Execute the queued request with timeout | |
| this._executeDirect(queueItem.requestFn, queueItem.timeoutMs) | |
| .then(queueItem.resolve) | |
| .catch(queueItem.reject); | |
| } | |
| } | |
| getMetrics() { | |
| return { | |
| ...this.metrics, | |
| activeRequests: this.activeRequests, | |
| queueLength: this.queue.length, | |
| maxConcurrent: this.maxConcurrent, | |
| maxQueueSize: this.maxQueueSize, | |
| utilization: (this.activeRequests / this.maxConcurrent * 100).toFixed(1) + '%' | |
| }; | |
| } | |
| clear() { | |
| this.queue.forEach(item => { | |
| item.reject(new Error('Queue cleared during shutdown')); | |
| }); | |
| this.queue = []; | |
| } | |
| } | |
| // Initialize request queue with optimized settings for Hugging Face | |
| const requestQueue = new RequestQueue( | |
| CONFIG.MAX_CONCURRENT_REQUESTS, // Conservative for 2 vCPU | |
| CONFIG.MAX_QUEUE_SIZE // Prevent memory issues | |
| ); | |
| // ============================================ | |
| // SERVER IMPLEMENTATION | |
| // ============================================ | |
| const server = Bun.serve({ | |
| port: CONFIG.PORT, | |
| hostname: '0.0.0.0', // Listen on all interfaces | |
| async fetch(req) { | |
| const start = Date.now(); | |
| const url = new URL(req.url); | |
| const path = url.pathname; | |
| const method = req.method; | |
| const clientIP = server.requestIP(req)?.address || 'unknown'; | |
| // Handle CORS Preflight | |
| if (method === 'OPTIONS') { | |
| return new Response(null, { | |
| status: 204, | |
| headers: getCorsHeaders() | |
| }); | |
| } | |
| // Rate Limiting | |
| if (!rateLimiter.check(clientIP)) { | |
| logger.warn('Rate limit exceeded', { ip: clientIP }); | |
| return createErrorResponse( | |
| 'Too many requests', | |
| 429, | |
| { | |
| retryAfter: Math.round(CONFIG.RATE_LIMIT_WINDOW_MS / 1000), | |
| limit: CONFIG.RATE_LIMIT_MAX_REQUESTS, | |
| window: Math.round(CONFIG.RATE_LIMIT_WINDOW_MS / 60000), | |
| message: `Rate limit exceeded. Maximum ${CONFIG.RATE_LIMIT_MAX_REQUESTS} requests per ${Math.round(CONFIG.RATE_LIMIT_WINDOW_MS / 60000)} minutes.` | |
| } | |
| ); | |
| } | |
| // Route Dispatcher with Request Queue | |
| let response; | |
| try { | |
| if (path === '/') { | |
| // High priority for image compression requests | |
| response = await requestQueue.execute( | |
| () => handleProxy(req, url), | |
| 'high' | |
| ); | |
| } else if (path === '/upload') { | |
| // High priority for image upload | |
| response = await requestQueue.execute( | |
| () => handleUpload(req, url), | |
| 'high' | |
| ); | |
| } else if (path === '/health') { | |
| // Normal priority for health checks | |
| response = await requestQueue.execute( | |
| () => handleHealth(), | |
| 'normal' | |
| ); | |
| } else if (path === '/metrics') { | |
| // Normal priority for metrics | |
| response = await requestQueue.execute( | |
| () => handleMetrics(), | |
| 'normal' | |
| ); | |
| } else if (path === '/clear') { | |
| // Normal priority for console clear | |
| response = await requestQueue.execute( | |
| () => handleClearConsole(), | |
| 'normal' | |
| ); | |
| } else if (path === '/favicon.ico') { | |
| response = new Response(null, { status: 204 }); | |
| } else { | |
| response = createErrorResponse( | |
| 'Not Found', | |
| 404, | |
| { path, method } | |
| ); | |
| } | |
| } catch (err) { | |
| // Handle queue overflow specifically | |
| if (err.message === 'Request queue full - server overloaded') { | |
| logger.warn('Request queue overflow', { | |
| ip: clientIP, | |
| path, | |
| queueMetrics: requestQueue.getMetrics() | |
| }); | |
| response = createErrorResponse( | |
| 'Server temporarily overloaded', | |
| 503, | |
| { | |
| retryAfter: 5, | |
| message: 'Too many concurrent requests. Please try again in a few seconds.', | |
| queueStatus: requestQueue.getMetrics() | |
| } | |
| ); | |
| } else if (err.message === 'Request timeout') { | |
| logger.warn('Request timeout', { | |
| ip: clientIP, | |
| path, | |
| queueMetrics: requestQueue.getMetrics() | |
| }); | |
| response = createErrorResponse( | |
| 'Request timeout', | |
| 408, | |
| { | |
| message: 'Request took too long to process. Please try again.', | |
| timeout: CONFIG.QUEUE_TIMEOUT_MS / 1000 + 's' | |
| } | |
| ); | |
| } else { | |
| logger.error('Unhandled error', { | |
| error: err ? err.message || String(err) : 'Unknown error', | |
| stack: err ? err.stack : undefined, | |
| method, | |
| path, | |
| ip: clientIP | |
| }); | |
| response = createErrorResponse( | |
| 'Internal Server Error', | |
| 500, | |
| process.env.NODE_ENV !== 'production' ? { | |
| details: err ? err.message || String(err) : 'Unknown error', | |
| stack: err ? err.stack : undefined, | |
| method, | |
| path | |
| } : {} | |
| ); | |
| } | |
| } | |
| // Add Security & CORS Headers | |
| addSecurityHeaders(response.headers); | |
| addCorsHeaders(response.headers); | |
| // Gzip Compression (if not already compressed image) | |
| const acceptEncoding = req.headers.get('Accept-Encoding') || ''; | |
| if (acceptEncoding.includes('gzip') && | |
| !response.headers.get('Content-Type')?.startsWith('image/') && | |
| !response.headers.get('Content-Encoding')) { | |
| try { | |
| // Read body | |
| const body = await response.arrayBuffer(); | |
| if (body.byteLength > 1024) { // Only compress if > 1KB | |
| const compressedStream = new Blob([body]).stream().pipeThrough(new CompressionStream('gzip')); | |
| const headers = new Headers(response.headers); | |
| headers.set('Content-Encoding', 'gzip'); | |
| headers.set('Vary', 'Accept-Encoding'); | |
| headers.delete('Content-Length'); | |
| response = new Response(compressedStream, { | |
| status: response.status, | |
| headers: headers | |
| }); | |
| } else { | |
| // Reconstruct response because we read the body | |
| response = new Response(body, { | |
| status: response.status, | |
| headers: response.headers | |
| }); | |
| } | |
| } catch (e) { | |
| logger.error('Gzip compression failed', { error: e.message }); | |
| } | |
| } | |
| // Logging | |
| const duration = Date.now() - start; | |
| const logData = { | |
| method, | |
| path, | |
| statusCode: response.status, | |
| duration: `${duration}ms`, | |
| ip: clientIP, | |
| userAgent: req.headers.get('User-Agent')?.substring(0, 100) | |
| }; | |
| if (url.searchParams.has('url')) { | |
| logData.imageUrl = url.searchParams.get('url').substring(0, 80); | |
| } | |
| if (response.status >= 400) { | |
| requestLogger.warn('Request completed with error', logData); | |
| } else { | |
| requestLogger.debug('Request completed', logData); | |
| } | |
| return response; | |
| }, | |
| error(error) { | |
| logger.error('Server error', { error: error.message, stack: error.stack }); | |
| return createErrorResponse( | |
| 'Internal Server Error', | |
| 500, | |
| process.env.NODE_ENV !== 'production' ? { | |
| details: error.message, | |
| stack: error.stack | |
| } : {} | |
| ); | |
| } | |
| }); | |
| console.error(`[START] ✅ Server running on port ${server.port}`); | |
| console.error(`[START] 🔗 Health check: http://localhost:${server.port}/health`); | |
| // ============================================ | |
| // HANDLERS | |
| // ============================================ | |
| async function handleProxy(req, url) { | |
| const startTime = Date.now(); | |
| let imageUrl = url.searchParams.get('url'); | |
| const memoryBefore = process.memoryUsage(); | |
| // Generate cache key (simplified for Bun Request) | |
| // We need to mock the req object expected by cacheWrapper or modify cacheWrapper | |
| // For now, let's manually construct the key as cacheWrapper does: | |
| // key = `pixelpinch:${imageUrl}:${params.quality}:${params.webp}:${params.avif}:${params.grayscale}` | |
| // But cacheWrapper.generateKey takes 'req'. Let's look at cacheWrapper later. | |
| // Assuming we can use a similar logic here. | |
| if (!imageUrl || typeof imageUrl !== 'string' || imageUrl.trim() === '') { | |
| // Bandwidth Hero extension validation requires this exact response | |
| return new Response('bandwidth-hero-proxy', { | |
| status: 200, | |
| headers: { | |
| 'Content-Type': 'text/plain' | |
| } | |
| }); | |
| } | |
| // Decode URL | |
| imageUrl = safeDecodeURI(imageUrl); | |
| // Validate URL | |
| if (!isValidImageUrl(imageUrl)) { | |
| return createErrorResponse( | |
| 'Invalid image URL', | |
| 400, | |
| { | |
| imageUrl: imageUrl.substring(0, 100), | |
| details: 'The provided URL is not valid or not supported' | |
| } | |
| ); | |
| } | |
| const queryParams = Object.fromEntries(url.searchParams); | |
| const params = parseParams(queryParams); | |
| const acceptHeader = req.headers.get('accept') || req.headers.get('Accept') || req.headers.get('ACCEPT') || ''; | |
| // Generate Cache Key | |
| const cacheKey = cacheWrapper.generateKey(imageUrl, queryParams, acceptHeader); | |
| try { | |
| // Check cache | |
| let cachedResult; | |
| try { | |
| cachedResult = await cacheWrapper.get(cacheKey); | |
| } catch (cacheError) { | |
| logger.warn('Cache get failed', { error: cacheError.message, cacheKey }); | |
| cachedResult = null; | |
| } | |
| if (cachedResult) { | |
| compressionLogger.debug('Cache hit served', { | |
| cacheKey, | |
| originalSize: cachedResult.originalSize, | |
| compressedSize: cachedResult.size, | |
| format: cachedResult.format, | |
| saved: cachedResult.saved | |
| }); | |
| const headers = new Headers(); | |
| headers.set('X-Cache', 'HIT'); | |
| headers.set('X-Cache-Age', Math.floor((Date.now() - cachedResult.timestamp) / 1000)); | |
| return createCompressedResponse(cachedResult.data, cachedResult.format, cachedResult.originalSize, cachedResult.size, cachedResult.compressionMethod || 'local', headers); | |
| } | |
| // Fetch image - pass original request headers to help bypass 403 errors | |
| const originalHeaders = { | |
| 'user-agent': req.headers.get('user-agent'), | |
| 'referer': req.headers.get('referer'), | |
| 'accept': req.headers.get('accept'), | |
| 'accept-language': req.headers.get('accept-language') | |
| }; | |
| const fetchResult = await fetchImage(imageUrl, { originalHeaders, signal: req.signal }); | |
| if (!fetchResult.ok) { | |
| // Error handling logic | |
| const is403Error = fetchResult.status === 403 || fetchResult.error?.includes('403'); | |
| const isProblematicDomain = CONFIG.PROBLEMATIC_DOMAINS.some(domain => imageUrl.includes(domain)); | |
| if (is403Error || isProblematicDomain) { | |
| securityLogger.warn('403 Forbidden detected', { url: imageUrl, error: fetchResult.error }); | |
| const headers = new Headers(); | |
| headers.set('X-Proxy-Error', '403-Forbidden'); | |
| headers.set('X-Proxy-Reason', 'Source server blocks automated requests'); | |
| // Return structured error response instead of redirect for API clients | |
| const acceptHeader = req.headers.get('accept') || ''; | |
| if (acceptHeader.includes('application/json')) { | |
| return createErrorResponse( | |
| 'Access forbidden by source server', | |
| 403, | |
| { | |
| imageUrl: imageUrl.substring(0, 100), | |
| reason: 'Source server blocks automated requests', | |
| isProblematicDomain | |
| } | |
| ); | |
| } | |
| return createRedirect(imageUrl, headers); | |
| } | |
| // Handle other fetch errors | |
| if (fetchResult.status >= 400 && fetchResult.status < 500) { | |
| return createErrorResponse( | |
| 'Source image not accessible', | |
| fetchResult.status, | |
| { | |
| imageUrl: imageUrl.substring(0, 100), | |
| sourceStatus: fetchResult.status, | |
| details: fetchResult.error || 'Source server returned error' | |
| } | |
| ); | |
| } | |
| return createRedirect(imageUrl); | |
| } | |
| const originalSize = fetchResult.buffer.length; | |
| // Adaptive quality | |
| params.quality = calculateAdaptiveQuality(params.quality, originalSize); | |
| // Compress | |
| compressionLogger.debug(`Accept header: "${acceptHeader}"`); | |
| // compressionLogger.debug(`All request headers: ${JSON.stringify(Object.keys(reqHeaders))}`); // Disabled for performance | |
| compressionLogger.debug('Compression params before compression', params); | |
| compressionLogger.debug(`Starting compression for ${formatBytes(fetchResult.buffer.length)} image...`); | |
| const result = await compressImage(fetchResult.buffer, params, acceptHeader); | |
| compressionLogger.debug('Compression result', { | |
| ok: result.ok, | |
| format: result.format || 'N/A', | |
| size: result.size || 'N/A', | |
| error: result.error || 'none', | |
| bypassed: result.bypassed || false | |
| }); | |
| if (!result.ok) { | |
| compressionLogger.debug('Compression failed, redirecting to original URL', { error: result.error }); | |
| return createRedirect(imageUrl); | |
| } | |
| const compressedSize = result.data.length; | |
| const savedBytes = originalSize - compressedSize; | |
| const savedPercent = ((savedBytes / originalSize) * 100).toFixed(1); | |
| const minSavingsPercent = CONFIG.MIN_SAVINGS_PERCENT || 0; | |
| // Check if compression was bypassed (smart bypass returns original) | |
| if (result.bypassed) { | |
| compressionLogger.debug('Compression bypassed - serving original image', { | |
| originalSize, | |
| reason: 'Compression would increase file size' | |
| }); | |
| const headers = new Headers(); | |
| headers.set('X-Compression-Bypassed', 'true'); | |
| headers.set('X-Bypass-Reason', 'Compression increased file size'); | |
| return createCompressedResponse(result.data, result.format, originalSize, originalSize, 'bypassed', headers); | |
| } | |
| if (savedBytes <= 0 || parseFloat(savedPercent) < minSavingsPercent) { | |
| return createRedirect(imageUrl); | |
| } | |
| // Log success | |
| const elapsed = Date.now() - startTime; | |
| const memoryAfter = process.memoryUsage(); | |
| const memoryUsed = Math.round((memoryAfter.heapUsed - memoryBefore.heapUsed) / 1024 / 1024); | |
| compressionLogger.info('Compression successful', { | |
| originalSize: formatBytes(originalSize), | |
| compressedSize: formatBytes(compressedSize), | |
| savedPercent: `${savedPercent}%`, | |
| format: result.format, | |
| elapsed: `${elapsed}ms`, | |
| memoryUsed: `+${memoryUsed}MB` | |
| }); | |
| // Cache | |
| if (cacheWrapper.shouldCache(result)) { | |
| try { | |
| const cacheData = { | |
| ...result, | |
| timestamp: Date.now(), | |
| originalSize, | |
| compressionMethod: 'local' | |
| }; | |
| await cacheWrapper.set(cacheKey, cacheData, CONFIG.CACHE_TTL); | |
| } catch (cacheError) { | |
| logger.warn('Cache set failed', { error: cacheError.message, cacheKey }); | |
| } | |
| } | |
| const headers = new Headers(); | |
| headers.set('X-Cache', 'MISS'); | |
| return createCompressedResponse(result.data, result.format, originalSize, compressedSize, 'local', headers); | |
| } catch (err) { | |
| compressionLogger.error('Compression failed', { error: err.message, imageUrl }); | |
| // Determine appropriate error response based on error type | |
| if (err.message.includes('Invalid image') || err.message.includes('Unsupported format')) { | |
| return createErrorResponse( | |
| 'Unsupported image format', | |
| 415, | |
| { | |
| imageUrl: imageUrl.substring(0, 100), | |
| details: err.message | |
| } | |
| ); | |
| } else if (err.message.includes('timeout') || err.message.includes('ETIMEDOUT')) { | |
| return createErrorResponse( | |
| 'Image processing timeout', | |
| 408, | |
| { | |
| imageUrl: imageUrl.substring(0, 100), | |
| details: 'The image took too long to process' | |
| } | |
| ); | |
| } else if (err.message.includes('memory') || err.message.includes('ENOMEM')) { | |
| return createErrorResponse( | |
| 'Insufficient memory for image processing', | |
| 507, | |
| { | |
| imageUrl: imageUrl.substring(0, 100), | |
| details: 'Image too large to process with available memory' | |
| } | |
| ); | |
| } else { | |
| return createRedirect(imageUrl); | |
| } | |
| } | |
| } | |
| function handleHealth() { | |
| const mem = process.memoryUsage(); | |
| const uptime = process.uptime(); | |
| const cacheStats = cacheWrapper.getStats(); | |
| const queueMetrics = requestQueue.getMetrics(); | |
| const stats = { | |
| status: 'ok', | |
| service: 'pixelpinch-proxy', | |
| platform: 'huggingface-free', | |
| version: '2.1.0-enhanced', | |
| timestamp: new Date().toISOString(), | |
| uptime: Math.floor(uptime), | |
| compression: { | |
| max_input_size: CONFIG.MAX_INPUT_SIZE, | |
| max_pixels: CONFIG.MAX_PIXELS, | |
| default_quality: CONFIG.DEFAULT_QUALITY | |
| }, | |
| performance: { | |
| memory: { | |
| heap_used: Math.round(mem.heapUsed / 1024 / 1024) + 'MB', | |
| heap_total: Math.round(mem.heapTotal / 1024 / 1024) + 'MB', | |
| rss: Math.round(mem.rss / 1024 / 1024) + 'MB' | |
| }, | |
| cpu_usage: process.cpuUsage() | |
| }, | |
| queue: queueMetrics, | |
| cache: cacheStats | |
| }; | |
| return new Response(JSON.stringify(stats), { | |
| headers: { 'Content-Type': 'application/json' } | |
| }); | |
| } | |
| function handleMetrics() { | |
| return new Response(JSON.stringify(performanceMonitor.getMetrics()), { | |
| headers: { 'Content-Type': 'application/json' } | |
| }); | |
| } | |
| function handleClearConsole() { | |
| // Clear the console using the logger's clear method | |
| logger.clearConsole(); | |
| // Log a confirmation message | |
| logger.debug('Console cleared via /clear endpoint'); | |
| return new Response(JSON.stringify({ | |
| status: 'ok', | |
| message: 'Console cleared successfully', | |
| timestamp: new Date().toISOString() | |
| }), { | |
| headers: { 'Content-Type': 'application/json' } | |
| }); | |
| } | |
| async function handleUpload(req, url) { | |
| const startTime = Date.now(); | |
| const memoryBefore = process.memoryUsage(); | |
| if (req.method !== 'POST') { | |
| return createErrorResponse('Method Not Allowed', 405, { details: 'Upload endpoint requires POST method' }); | |
| } | |
| let file; | |
| try { | |
| const formData = await req.formData(); | |
| file = formData.get('image'); | |
| if (!file) { | |
| return createErrorResponse('Bad Request', 400, { details: 'Missing image file in form data' }); | |
| } | |
| } catch (err) { | |
| return createErrorResponse('Bad Request', 400, { details: 'Failed to parse form data' }); | |
| } | |
| const originalSize = file.size; | |
| const arrayBuffer = await file.arrayBuffer(); | |
| const buffer = Buffer.from(arrayBuffer); | |
| const queryParams = Object.fromEntries(url.searchParams); | |
| const params = parseParams(queryParams); | |
| const acceptHeader = req.headers.get('accept') || ''; | |
| try { | |
| // Adaptive quality | |
| params.quality = calculateAdaptiveQuality(params.quality, originalSize); | |
| compressionLogger.debug('Compression params before compression', params); | |
| compressionLogger.debug(`Starting compression for ${formatBytes(originalSize)} uploaded image...`); | |
| const result = await compressImage(buffer, params, acceptHeader); | |
| if (!result.ok) { | |
| return createErrorResponse('Compression failed', 500, { details: result.error }); | |
| } | |
| const compressedSize = result.data.length; | |
| const savedBytes = originalSize - compressedSize; | |
| const savedPercent = ((savedBytes / originalSize) * 100).toFixed(1); | |
| if (result.bypassed) { | |
| const headers = new Headers(); | |
| headers.set('X-Compression-Bypassed', 'true'); | |
| headers.set('X-Bypass-Reason', 'Compression increased file size'); | |
| return createCompressedResponse(result.data, result.format, originalSize, originalSize, 'bypassed', headers); | |
| } | |
| const elapsed = Date.now() - startTime; | |
| const memoryAfter = process.memoryUsage(); | |
| const memoryUsed = Math.round((memoryAfter.heapUsed - memoryBefore.heapUsed) / 1024 / 1024); | |
| compressionLogger.info('Upload Compression successful', { | |
| originalSize: formatBytes(originalSize), | |
| compressedSize: formatBytes(compressedSize), | |
| savedPercent: `${savedPercent}%`, | |
| format: result.format, | |
| elapsed: `${elapsed}ms`, | |
| memoryUsed: `+${memoryUsed}MB` | |
| }); | |
| const headers = new Headers(); | |
| headers.set('X-Cache', 'BYPASS'); | |
| return createCompressedResponse(result.data, result.format, originalSize, compressedSize, 'local', headers); | |
| } catch (err) { | |
| compressionLogger.error('Upload Compression failed', { error: err.message }); | |
| return createErrorResponse('Image processing failed', 500, { details: err.message }); | |
| } | |
| } | |
| // Memory logging | |
| setInterval(() => { | |
| const mem = process.memoryUsage(); | |
| const used = Math.round(mem.heapUsed / 1024 / 1024); | |
| const total = Math.round(mem.heapTotal / 1024 / 1024); | |
| logger.debug('Memory usage', { heap_used: `${used}MB`, heap_total: `${total}MB` }); | |
| }, 30000); | |
| // Graceful shutdown with queue cleanup | |
| process.on('SIGTERM', () => { | |
| logger.info('Server stopping - clearing request queue...'); | |
| // Clear the request queue to reject pending requests | |
| requestQueue.clear(); | |
| // Log final queue metrics | |
| const finalMetrics = requestQueue.getMetrics(); | |
| logger.info('Final queue metrics', finalMetrics); | |
| server.stop(); | |
| process.exit(0); | |
| }); | |
| process.on('SIGINT', () => { | |
| logger.info('Server interrupted - clearing request queue...'); | |
| // Clear the request queue to reject pending requests | |
| requestQueue.clear(); | |
| // Log final queue metrics | |
| const finalMetrics = requestQueue.getMetrics(); | |
| logger.info('Final queue metrics', finalMetrics); | |
| server.stop(); | |
| process.exit(0); | |
| }); | |