Deploy habadashi_login gateway
Browse filesFiles changed (4)
- README.md+60
- app.py+106-17
- bootstrap.py+54-12
- requirements.txt+1
34 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969734 unmodified lines3. User logs in with Supabase credentials
4. On successful login, ver20 Gradio app is mounted at `/app/`
5. User profile and organization info loaded from `profiles` table
## Startup Phase Logging
The application logs structured startup phases to help diagnose issues. Look for these phase markers in the logs:
### Expected Startup Sequence
1. `[STARTUP_META]` - Environment and configuration info
2. `[PHASE] bootstrap_start` - Begin downloading private app
3. `[PHASE] bootstrap_end success=true` - Private app downloaded
4. `[PHASE] supabase_init_start` - Initialize Supabase client
5. `[PHASE] supabase_init_end success=true` - Supabase ready
6. `[PHASE] fastapi_init_start/end` - FastAPI app created
7. `[PHASE] create_ui_start/end` - Login UI created
8. `[PHASE] import_ver20_start` - Import ver20 app
9. `[PHASE] import_ver20_end success=true` - Ver20 loaded
10. `[PHASE] mount_login_start/end` - Login UI mounted
11. `[PHASE] mount_app_start/end` - Ver20 app mounted
12. `[STARTUP_COMPLETE]` - All phases complete
### Health Check Endpoint
Once started, check the health endpoint:
```bash
curl https://your-space.hf.space/healthz
```
Expected response:
```json
{
"ok": true,
"ver20_loaded": true,
"private_app_dir": "./private_app"
}
```
### Debugging Startup Failures
If the Space fails to start or restarts repeatedly:
1. **Check the last phase reached** in logs
2. **Look for `[ERROR]` and `[TRACEBACK]` markers** after the last phase
3. **Common failure points:**
- `bootstrap_end success=false` - HF_TOKEN missing or invalid
- `supabase_init_end success=false` - SUPABASE_URL/KEY missing
- `import_ver20_end success=false` - Ver20 app.py structure issue
- No phases after `mount_app_end` - Port binding or health check issue
### Request Logging
All HTTP requests are logged with:
- `[REQUEST]` - Incoming request (method, path)
- `[RESPONSE]` - Response status and duration
Example:
```
[REQUEST] method=GET path=/
[RESPONSE] method=GET path=/ status=307 duration=0.015s
```5 unmodified lines67891011121113141516171 unmodified line192021222324252627282930313233343536373820394041421 unmodified line44454628474849315051525354555657585960616263646566676845697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211 unmodified line123124125697012612712812917 unmodified lines14714814994150151152153981541551561571581591601611621631641651661671681691111701711131141721731741751761771781791801811821831841851 unmodified line1871881891901911921931941951961971981992002012022032042052062072081322092102112122132142152161382172182192201 unmodified line2222232241461471482252262272282292302312322332342352362375 unmodified lines
import os
import sys
import time
import traceback
from pathlib import Path
from fastapi import FastAPI, Request, Depends, HTTPException
from fastapi.responses import RedirectResponse
from fastapi.responses import RedirectResponse, JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
import gradio as gr
from supabase import create_client, Client
1 unmodified linefrom bootstrap import download_private_app
from login import create_login_ui
# --- Startup Meta Info ---
print("=" * 80)
print("π Starting Habadashi Login Gateway")
print("=" * 80)
print(f"[STARTUP_META] Python version: {sys.version}")
print(f"[STARTUP_META] CWD: {os.getcwd()}")
print(f"[STARTUP_META] PORT: {os.environ.get('PORT', 'not set')}")
print(f"[STARTUP_META] SPACE_ID: {os.environ.get('SPACE_ID', 'not set')}")
print(f"[STARTUP_META] SPACE_HOST: {os.environ.get('SPACE_HOST', 'not set')}")
print(f"[STARTUP_META] GRADIO_SERVER_NAME: {os.environ.get('GRADIO_SERVER_NAME', 'not set')}")
print(f"[STARTUP_META] GRADIO_SERVER_PORT: {os.environ.get('GRADIO_SERVER_PORT', 'not set')}")
print(f"[STARTUP_META] HF_TOKEN: {'***set***' if os.environ.get('HF_TOKEN') else 'NOT SET'}")
print(f"[STARTUP_META] SUPABASE_URL: {'***set***' if os.environ.get('SUPABASE_URL') else 'NOT SET'}")
print(f"[STARTUP_META] SUPABASE_KEY: {'***set***' if os.environ.get('SUPABASE_KEY') else 'NOT SET'}")
print("=" * 80)
# --- Bootstrap: Download private app at startup ---
print("π Starting Habadashi Login Gateway...")
print("[PHASE] bootstrap_start")
try:
private_app_dir = download_private_app()
1 unmodified line private_app_path = str(private_app_dir.resolve())
if private_app_path not in sys.path:
sys.path.insert(0, private_app_path)
print(f"β
Added to Python path: {private_app_path}")
print(f"[PHASE] bootstrap_end success=true path={private_app_path}")
except Exception as e:
print(f"β Failed to bootstrap private app: {e}")
print(f"[PHASE] bootstrap_end success=false")
print(f"[ERROR] Bootstrap failed: {e}")
print(f"[TRACEBACK]\n{traceback.format_exc()}")
print("β οΈ Application will start but /app/ route will not work")
private_app_dir = None
# --- Supabase Setup ---
print("[PHASE] supabase_init_start")
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
if not SUPABASE_URL or not SUPABASE_KEY:
print("[ERROR] SUPABASE_URL and/or SUPABASE_KEY not set")
raise ValueError(
"SUPABASE_URL and SUPABASE_KEY must be set in environment variables. "
"Please configure them in HF Space Secrets."
)
try:
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
print(f"[PHASE] supabase_init_end success=true")
except Exception as e:
print(f"[PHASE] supabase_init_end success=false")
print(f"[ERROR] Supabase init failed: {e}")
print(f"[TRACEBACK]\n{traceback.format_exc()}")
raise
# --- FastAPI App ---
print("[PHASE] fastapi_init_start")
app = FastAPI()
print("[PHASE] fastapi_init_end")
# --- Request Logging Middleware ---
class RequestLoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start_time = time.time()
path = request.url.path
method = request.method
print(f"[REQUEST] method={method} path={path}")
try:
response = await call_next(request)
duration = time.time() - start_time
print(f"[RESPONSE] method={method} path={path} status={response.status_code} duration={duration:.3f}s")
return response
except Exception as e:
duration = time.time() - start_time
print(f"[RESPONSE] method={method} path={path} status=500 duration={duration:.3f}s error={e}")
raise
app.add_middleware(RequestLoggingMiddleware)
print("[MIDDLEWARE] RequestLoggingMiddleware added")
# --- Authentication Handler (for login UI) ---
def handle_login(email, password):
"""Handle login attempt via Supabase"""
print(f"[AUTH] Login attempt for: {email}")
try:
res = supabase.auth.sign_in_with_password({"email": email, "password": password})
if res.session:
print(f"[AUTH] Login successful: {email}")
return (
gr.update(visible=False),
gr.update(visible=True, value=f"### β
γγ°γ€γ³ζε: {email}"),
res.session.access_token
)
except Exception as e:
print(f"[AUTH] Login failed for {email}: {e}")
return gr.update(), gr.update(value=f"β γ¨γ©γΌ: {str(e)}"), None
# --- Authentication Dependency ---1 unmodified line """Verify token from cookie and fetch user profile"""
token = request.cookies.get("sb_access_token")
print(f"--- Auth Check ---")
print(f"Token present: {bool(token)}")
print(f"[AUTH_CHECK] Token present: {bool(token)}")
if not token:
return None17 unmodified lines "org_name": (profile_data.get("organizations") or {}).get("name")
}
print(f"Auth Success: {user_dict['email']}")
print(f"[AUTH_CHECK] Success: user={user_dict['email']} role={user_dict['role']}")
return user_dict
except Exception as e:
print(f"Auth Error: {e}")
print(f"[AUTH_CHECK] Failed: {e}")
return None
# --- Create UI instances ---
print("[PHASE] create_ui_start")
login_ui = create_login_ui(handle_login)
print("[PHASE] create_ui_end component=login_ui")
# Import ver20 app (Gradio Blocks)
print("[PHASE] import_ver20_start")
ver20_app = None
if private_app_dir:
try:
# Import app module from downloaded private app
from app import app as ver20_blocks
ver20_app = ver20_blocks
print("β
Successfully imported ver20 Gradio app")
print(f"[PHASE] import_ver20_end success=true type={type(ver20_app)}")
except Exception as e:
print(f"β Failed to import ver20 app: {e}")
print(f" Make sure ver20/app.py exports 'app' variable (Gradio Blocks)")
print(f"[PHASE] import_ver20_end success=false")
print(f"[ERROR] Failed to import ver20 app: {e}")
print(f"[TRACEBACK]\n{traceback.format_exc()}")
else:
print(f"[PHASE] import_ver20_end success=false reason=bootstrap_failed")
# --- Routes ---
@app.get("/")
async def root(user=Depends(get_current_user)):
"""Root route - redirect to login or app based on auth status"""
print(f"[ROUTE] / accessed, user_authenticated={isinstance(user, dict) and user.get('user_id')}")
if isinstance(user, dict) and user.get("user_id"):
return RedirectResponse(url="/app/")
return RedirectResponse(url="/login/")1 unmodified line@app.get("/logout")
async def logout():
"""Logout route - clear cookie and redirect to login"""
print(f"[ROUTE] /logout accessed")
response = RedirectResponse(url="/login/")
response.delete_cookie("sb_access_token")
return response
@app.get("/healthz")
async def healthz():
"""Health check endpoint"""
status = {
"ok": True,
"ver20_loaded": ver20_app is not None,
"private_app_dir": str(private_app_dir) if private_app_dir else None
}
print(f"[HEALTHZ] {status}")
return JSONResponse(content=status)
print("[ROUTES] Root, logout, and healthz routes registered")
# --- Mount Gradio UIs ---
# Login UI (public)
print("[PHASE] mount_login_start")
app = gr.mount_gradio_app(app, login_ui, path="/login")
print("[PHASE] mount_login_end path=/login")
# Ver20 App (protected)
print("[PHASE] mount_app_start")
if ver20_app:
app = gr.mount_gradio_app(app, ver20_app, path="/app", auth_dependency=get_current_user)
print("β
Mounted ver20 app at /app/ (protected)")
print("[PHASE] mount_app_end path=/app protected=true ver20=true")
else:
# Fallback: simple placeholder if ver20 failed to load
with gr.Blocks() as fallback_ui:1 unmodified line gr.Markdown("The private application failed to load. Please check logs.")
app = gr.mount_gradio_app(app, fallback_ui, path="/app", auth_dependency=get_current_user)
print("β οΈ Mounted fallback UI at /app/ (ver20 failed to load)")
print("π Habadashi Login Gateway ready!") print("[PHASE] mount_app_end path=/app protected=true ver20=false fallback=true")
print("=" * 80)
print("π Habadashi Login Gateway Ready!")
print("=" * 80)
print(f"[STARTUP_COMPLETE] All phases completed successfully")
print(f"[STARTUP_COMPLETE] Access URLs:")
print(f" - Root: /")
print(f" - Login: /login/")
print(f" - App: /app/")
print(f" - Health: /healthz")
print(f" - Logout: /logout")
print("=" * 80)10 unmodified lines11121314151617181920212210 unmodified lines3334353637383940414243444546394748495051525342545556575847596061626364526566675668697059606162636471727374756976777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511610 unmodified lines """Get HF_TOKEN from environment variable"""
token = os.environ.get("HF_TOKEN")
if not token:
print("[BOOTSTRAP_ERROR] HF_TOKEN not found in environment")
raise ValueError(
"HF_TOKEN not found. Please set HF_TOKEN environment variable "
"in HF Space Secrets to access private repository."
)
print("[BOOTSTRAP] HF_TOKEN found (length: ***)")
return token
def download_private_app(force_download: bool = False):10 unmodified lines repo_type = "space"
local_dir = Path("./private_app")
print(f"[BOOTSTRAP] Starting download")
print(f"[BOOTSTRAP] repo_id={repo_id} repo_type={repo_type}")
print(f"[BOOTSTRAP] local_dir={local_dir} force_download={force_download}")
print(f"[BOOTSTRAP] local_dir.exists()={local_dir.exists()}")
# Check if already downloaded (skip if exists and not forced)
if local_dir.exists() and not force_download:
# Verify essential files exist
app_py = local_dir / "app.py"
print(f"[BOOTSTRAP] Checking cache: app.py exists={app_py.exists()}")
if app_py.exists():
print(f"β
Private app already downloaded: {local_dir}")
print(f"[BOOTSTRAP] Using cached download: {local_dir}")
# Verify structure
_verify_downloaded_structure(local_dir)
return local_dir
else:
print(f"[BOOTSTRAP] Cache invalid (app.py missing), will re-download")
print(f"π Downloading private app from {repo_id}...")
print(f"[BOOTSTRAP] Starting fresh download from {repo_id}...")
try:
token = get_hf_token()
# Download entire Space repository
# Download entire Space repository (removed local_dir_use_symlinks - deprecated)
print(f"[BOOTSTRAP] Calling snapshot_download...")
snapshot_download(
repo_id=repo_id,
repo_type=repo_type,
local_dir=str(local_dir),
local_dir_use_symlinks=False,
token=token,
)
print(f"β
Download complete: {local_dir}")
print(f"[BOOTSTRAP] Download complete: {local_dir}")
# Verify essential structure
app_py = local_dir / "app.py"
if not app_py.exists():
raise FileNotFoundError(
f"app.py not found in downloaded repository. "
f"Expected at: {app_py}"
)
_verify_downloaded_structure(local_dir)
return local_dir
except Exception as e:
print(f"β Failed to download private app: {e}")
print(f"[BOOTSTRAP_ERROR] Download failed: {e}")
import traceback
print(f"[TRACEBACK]\n{traceback.format_exc()}")
raise
def _verify_downloaded_structure(local_dir: Path):
"""Verify downloaded structure has essential components"""
print(f"[BOOTSTRAP_VERIFY] Checking downloaded structure...")
essential_files = [
"app.py",
"requirements.txt",
]
essential_dirs = [
"lib",
"exec",
"core",
"presentation",
]
for file_name in essential_files:
file_path = local_dir / file_name
exists = file_path.exists()
print(f"[BOOTSTRAP_VERIFY] {file_name}: {'EXISTS' if exists else 'MISSING'}")
if not exists and file_name == "app.py":
raise FileNotFoundError(
f"Critical file missing: {file_name}. "
f"Expected at: {file_path}"
)
for dir_name in essential_dirs:
dir_path = local_dir / dir_name
exists = dir_path.exists() and dir_path.is_dir()
print(f"[BOOTSTRAP_VERIFY] {dir_name}/: {'EXISTS' if exists else 'MISSING'}")
print(f"[BOOTSTRAP_VERIFY] Verification complete")
if __name__ == "__main__":
# Test download
download_private_app()1234567# Public Gateway dependencies
fastapi
uvicorn
gradio
supabase
python-multipart
huggingface_hubREADME.md+60
app.py+106-17
bootstrap.py+54-12
requirements.txt+1