brain3 / app.py
Elliotasdasdasfasas
Fix Brain3: Lazy Tunnel Start to prevent 503
b33d06f
from fastapi import FastAPI, HTTPException
from azure_bridge import AzureSFTPBridge
import os
import time
app = FastAPI()
bridge = None
@app.on_event("startup")
async def startup_event():
global bridge
print("๐Ÿš€ Brain3 Starting (Lazy Bridge Mode)...")
# Initialize object but DO NOT start tunnel yet
try:
bridge = AzureSFTPBridge()
print("โœ… Bridge initialized (Tunnel Pending)")
except Exception as e:
print(f"โš ๏ธ Bridge init failed: {e}")
@app.get("/start-bridge")
def trigger_bridge():
"""Manually start the tunnel."""
global bridge
if not bridge: return {"error": "Bridge not init"}
if os.environ.get("SSH_KEY"):
# Start in thread to not block response
threading.Thread(target=bridge.start_tunnel, daemon=True).start()
return {"status": "Tunnel starting in background..."}
else:
return {"error": "SSH_KEY missing"}
@app.get("/")
def home():
return {"status": "Brain3 Online", "mode": "SFTP Tunnel"}
@app.get("/test-storage")
def test_storage():
"""Writes a test file to Azure and lists directory."""
global bridge
if not bridge:
return {"error": "Bridge not initialized"}
try:
# 1. Create dummy file
filename = f"brain3_probe_{int(time.time())}.txt"
with open(filename, "w") as f:
f.write(f"Hello from Brain3 via SFTP at {time.time()}")
# 2. Upload
remote_path = f"/mnt/lightrag/{filename}" # Assuming user has write access here
# Or try home dir if unsure:
# remote_path = f"/home/azureuser/{filename}"
bridge.upload_file(filename, remote_path)
# 3. List
files = bridge.list_files("/mnt/lightrag")
return {
"upload_status": "success",
"remote_path": remote_path,
"directory_listing": files
}
except Exception as e:
return {"error": str(e)}