#!/usr/bin/env python3 """ Startup script to run both Worker and API server """ import subprocess import sys import time import threading from loguru import logger def stream_output(process, prefix): """Stream subprocess output to main stdout""" for line in iter(process.stdout.readline, ''): if line: print(f"[{prefix}] {line.rstrip()}", flush=True) process.stdout.close() def main(): """Start worker and API server""" logger.info("🚀 Starting SWARA API with background worker...") # Start worker in background logger.info("Starting RQ Worker...") worker_process = subprocess.Popen( [sys.executable, "-m", "app.worker"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, # TEXT MODE (bukan binary) bufsize=1, # Line buffering (works with text mode) universal_newlines=True ) logger.info(f"✓ Worker started (PID: {worker_process.pid})") # Stream worker output in separate thread worker_thread = threading.Thread( target=stream_output, args=(worker_process, "WORKER"), daemon=True ) worker_thread.start() # Give worker a moment to initialize time.sleep(2) # Start API server in foreground logger.info("Starting API server...") api_process = subprocess.Popen( [sys.executable, "-m", "app.main"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, # TEXT MODE (bukan binary) bufsize=1, # Line buffering (works with text mode) universal_newlines=True ) logger.info(f"✓ API server started (PID: {api_process.pid})") # Stream API output in separate thread api_thread = threading.Thread( target=stream_output, args=(api_process, "API"), daemon=True ) api_thread.start() try: # Wait for API server (it runs in foreground) api_process.wait() except KeyboardInterrupt: logger.info("Shutting down...") worker_process.terminate() api_process.terminate() worker_process.wait() api_process.wait() if __name__ == "__main__": main()