Commit de5aaf26 authored by Lisa (AI Assistant)'s avatar Lisa (AI Assistant)

Fix Redis variable scope issue

- Fix UnboundLocalError: cannot access local variable 'REDIS_ENABLED'
- Create _use_redis variable to track actual backend in use
- Ensure proper Redis initialization and fallback logic
parent 77f5cccc
...@@ -84,10 +84,12 @@ AGENTS = {} ...@@ -84,10 +84,12 @@ AGENTS = {}
# Redis client # Redis client
REDIS_CLIENT = None REDIS_CLIENT = None
_use_redis = REDIS_ENABLED
async def init_redis(): async def init_redis():
"""Initialize Redis connection if REDIS_ENABLED""" """Initialize Redis connection if REDIS_ENABLED"""
global REDIS_CLIENT global REDIS_CLIENT
global _use_redis
if REDIS_ENABLED: if REDIS_ENABLED:
try: try:
import redis.asyncio as redis import redis.asyncio as redis
...@@ -98,13 +100,13 @@ async def init_redis(): ...@@ -98,13 +100,13 @@ async def init_redis():
except Exception as e: except Exception as e:
logger.error(f"Failed to connect to Redis: {e}") logger.error(f"Failed to connect to Redis: {e}")
logger.warning("Falling back to SQLite") logger.warning("Falling back to SQLite")
REDIS_ENABLED = False _use_redis = False
# Create FastMCP server # Create FastMCP server
mcp = FastMCP("ClawPhone", host=HOST, port=PORT) mcp = FastMCP("ClawPhone", host=HOST, port=PORT)
async def init_db(): async def init_db():
if REDIS_ENABLED: if _use_redis:
logger.info("Using Redis backend") logger.info("Using Redis backend")
else: else:
logger.info("Using SQLite backend") logger.info("Using SQLite backend")
...@@ -117,7 +119,7 @@ async def init_db(): ...@@ -117,7 +119,7 @@ async def init_db():
async def load_agents(): async def load_agents():
global AGENTS global AGENTS
if REDIS_ENABLED: if _use_redis:
# Load agents from Redis # Load agents from Redis
agents = await REDIS_CLIENT.hgetall("clawphone:agents") agents = await REDIS_CLIENT.hgetall("clawphone:agents")
AGENTS = {name: json.loads(data) for name, data in agents.items()} AGENTS = {name: json.loads(data) for name, data in agents.items()}
...@@ -149,7 +151,7 @@ async def init_token(): ...@@ -149,7 +151,7 @@ async def init_token():
elif os.getenv("CLAWPHONE_TOKEN"): elif os.getenv("CLAWPHONE_TOKEN"):
API_TOKEN = os.getenv("CLAWPHONE_TOKEN") API_TOKEN = os.getenv("CLAWPHONE_TOKEN")
else: else:
if REDIS_ENABLED: if _use_redis:
# Get token from Redis # Get token from Redis
API_TOKEN = await REDIS_CLIENT.get("clawphone:server_token") API_TOKEN = await REDIS_CLIENT.get("clawphone:server_token")
if not API_TOKEN: if not API_TOKEN:
...@@ -184,7 +186,7 @@ async def register(hook: str, token: str, name: str = None) -> str: ...@@ -184,7 +186,7 @@ async def register(hook: str, token: str, name: str = None) -> str:
"registered_at": datetime.now().isoformat() "registered_at": datetime.now().isoformat()
} }
if REDIS_ENABLED: if _use_redis:
await REDIS_CLIENT.hset("clawphone:agents", name, json.dumps(agent_data)) await REDIS_CLIENT.hset("clawphone:agents", name, json.dumps(agent_data))
else: else:
async with aiosqlite.connect(DB_PATH) as db: async with aiosqlite.connect(DB_PATH) as db:
...@@ -230,7 +232,7 @@ async def post_job(sender: str, target_agent: str, title: str, description: str ...@@ -230,7 +232,7 @@ async def post_job(sender: str, target_agent: str, title: str, description: str
"next_retry_at": None "next_retry_at": None
} }
if REDIS_ENABLED: if _use_redis:
await REDIS_CLIENT.hset("clawphone:jobs", job_id, json.dumps(job)) await REDIS_CLIENT.hset("clawphone:jobs", job_id, json.dumps(job))
else: else:
async with aiosqlite.connect(DB_PATH) as db: async with aiosqlite.connect(DB_PATH) as db:
...@@ -247,7 +249,7 @@ async def claim_job(job_id: str, agent: str) -> str: ...@@ -247,7 +249,7 @@ async def claim_job(job_id: str, agent: str) -> str:
if not job_id or not agent: if not job_id or not agent:
return json.dumps({"success": False, "error": "missing required"}) return json.dumps({"success": False, "error": "missing required"})
if REDIS_ENABLED: if _use_redis:
job_data = await REDIS_CLIENT.hget("clawphone:jobs", job_id) job_data = await REDIS_CLIENT.hget("clawphone:jobs", job_id)
if not job_data: if not job_data:
return json.dumps({"success": False, "error": "Not found"}) return json.dumps({"success": False, "error": "Not found"})
...@@ -280,7 +282,7 @@ async def reject_job(job_id: str, agent: str, reason: str = "") -> str: ...@@ -280,7 +282,7 @@ async def reject_job(job_id: str, agent: str, reason: str = "") -> str:
if not job_id or not agent: if not job_id or not agent:
return json.dumps({"success": False, "error": "missing required"}) return json.dumps({"success": False, "error": "missing required"})
if REDIS_ENABLED: if _use_redis:
job_data = await REDIS_CLIENT.hget("clawphone:jobs", job_id) job_data = await REDIS_CLIENT.hget("clawphone:jobs", job_id)
if not job_data: if not job_data:
return json.dumps({"success": False, "error": "Not found"}) return json.dumps({"success": False, "error": "Not found"})
...@@ -302,7 +304,7 @@ async def update_job_status(job_id: str, status: str, agent: str, result: str = ...@@ -302,7 +304,7 @@ async def update_job_status(job_id: str, status: str, agent: str, result: str =
if not all([job_id, status, agent]): if not all([job_id, status, agent]):
return json.dumps({"success": False, "error": "missing required"}) return json.dumps({"success": False, "error": "missing required"})
if REDIS_ENABLED: if _use_redis:
job_data = await REDIS_CLIENT.hget("clawphone:jobs", job_id) job_data = await REDIS_CLIENT.hget("clawphone:jobs", job_id)
if not job_data: if not job_data:
return json.dumps({"success": False, "error": "Not found"}) return json.dumps({"success": False, "error": "Not found"})
...@@ -330,7 +332,7 @@ async def update_job_status(job_id: str, status: str, agent: str, result: str = ...@@ -330,7 +332,7 @@ async def update_job_status(job_id: str, status: str, agent: str, result: str =
@mcp.tool() @mcp.tool()
async def list_jobs(agent: str = None, status: str = None) -> str: async def list_jobs(agent: str = None, status: str = None) -> str:
"""List jobs, optionally filtered by agent and status""" """List jobs, optionally filtered by agent and status"""
if REDIS_ENABLED: if _use_redis:
# Get jobs from Redis # Get jobs from Redis
jobs_data = await REDIS_CLIENT.hgetall("clawphone:jobs") jobs_data = await REDIS_CLIENT.hgetall("clawphone:jobs")
jobs = [json.loads(data) for data in jobs_data.values()] jobs = [json.loads(data) for data in jobs_data.values()]
...@@ -355,7 +357,7 @@ async def list_jobs(agent: str = None, status: str = None) -> str: ...@@ -355,7 +357,7 @@ async def list_jobs(agent: str = None, status: str = None) -> str:
@mcp.tool() @mcp.tool()
async def get_job(job_id: str) -> str: async def get_job(job_id: str) -> str:
"""Get job details""" """Get job details"""
if REDIS_ENABLED: if _use_redis:
job_data = await REDIS_CLIENT.hget("clawphone:jobs", job_id) job_data = await REDIS_CLIENT.hget("clawphone:jobs", job_id)
if job_data: if job_data:
job = json.loads(job_data) job = json.loads(job_data)
...@@ -380,8 +382,8 @@ async def main(): ...@@ -380,8 +382,8 @@ async def main():
logger.info(f" SERVER TOKEN: {API_TOKEN}") logger.info(f" SERVER TOKEN: {API_TOKEN}")
logger.info(f" MODE: {'HTTPS' if not args.plain else 'HTTP'}") logger.info(f" MODE: {'HTTPS' if not args.plain else 'HTTP'}")
logger.info(f" PORTS: {PORT}") logger.info(f" PORTS: {PORT}")
logger.info(f" DATABASE: {'Redis' if REDIS_ENABLED else 'SQLite'}") logger.info(f" DATABASE: {'Redis' if _use_redis else 'SQLite'}")
if REDIS_ENABLED: if _use_redis:
logger.info(f" REDIS URL: {REDIS_URL}") logger.info(f" REDIS URL: {REDIS_URL}")
else: else:
logger.info(f" DB PATH: {DB_PATH}") logger.info(f" DB PATH: {DB_PATH}")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment