load(); } // Helper to mimic your _env() helper if (!function_exists('_env')) { function _env($key, $default = null) { return $_ENV[$key] ?? $default; } } use App\Helpers\TinyRedis; use Monolog\Logger; use Aws\CloudWatchLogs\CloudWatchLogsClient; use App\Logging\CloudWatchHandler; echo "Lightweight Worker Started. Memory: " . round(memory_get_usage()/1024/1024, 2) . " MB\n"; $redis = null; $lockKey = 'audit_worker_running'; $lockDuration = 65; // 4. Manually Setup the Logger (replicating AuditLogServiceProvider logic) try { $config = [ 'region' => _env('AWS_DEFAULT_REGION', 'ap-south-1'), 'version' => _env('CLOUDWATCH_VERSION', 'latest'), 'credentials' => [ 'key' => _env('CLOUDWATCH_ACCESS_KEY'), 'secret' => _env('CLOUDWATCH_SECRET_KEY'), ] ]; $awsClient = new CloudWatchLogsClient($config); $logGroup = _env('CLOUDWATCH_GROUP', '/aws/cf-admin-laravel'); $handler = new CloudWatchHandler($awsClient, $logGroup); $logger = new Logger('audit'); $logger->pushHandler($handler); } catch (Exception $e) { die("CRITICAL: Could not setup Custom CloudWatch Logger. " . $e->getMessage() . "\n"); } // 5. The Worker Loop try { $redis = new TinyRedis( _env('REDIS_HOST', '127.0.0.1'), _env('REDIS_PORT', 6379) ); $lockAcquired = $redis->setnxEx($lockKey, '1', $lockDuration); if (trim($lockAcquired) !== "OK") { exit(0); } echo "Lock acquired. Processing queue...\n"; // 2. PROCESS QUEUE (Safe LPOP Method) $startTime = time(); $processedCount = 0; while (true) { if (time() - $startTime > 60) { echo "Time limit reached. Exiting to let next cron take over.\n"; break; } $jsonPayload = $redis->lpop('audit_queue'); // Returns string or null // If Redis returns null, the queue is empty. We are done. if (!$jsonPayload) { break; } // Process the payload $payload = json_decode($jsonPayload, true); if (is_array($payload)) { $logger->info('HTTP Audit', $payload); $processedCount++; } else { echo " [WARNING] Skipped invalid payload (Not an array): " . print_r($payload, true) . "\n"; } } echo "Queue drained. Processed $processedCount logs. Exiting.\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; }