apolinario commited on
Commit
c36b47d
·
1 Parent(s): e723ea7

robust disconnect logic

Browse files
Files changed (1) hide show
  1. app.py +46 -46
app.py CHANGED
@@ -427,58 +427,58 @@ async def websocket_video_gen(websocket: WebSocket, user_fal_key: Optional[str]
427
  active_websockets.add(websocket)
428
  print(f"WebSocket connected. Active connections: {len(active_websockets)}")
429
 
430
- # Get user from cookie
431
- access_token = websocket.cookies.get("access_token")
432
- if not access_token:
433
- await websocket.close(code=1008, reason="Not authenticated")
434
- return
435
-
436
  try:
437
- user_info = await get_user_info(access_token)
438
- except:
439
- await websocket.close(code=1008, reason="Invalid session")
440
- return
441
-
442
- # If user provided their own FAL key, use it (bypass limits)
443
- if user_fal_key:
444
- fal_key_to_use = user_fal_key
445
- else:
446
- # Check if user can start session with server FAL key
447
- can_start, used, limit = can_start_generation(user_info["username"], user_info["is_pro"])
448
- if not can_start:
449
- await websocket.close(code=1008, reason=f"Daily limit reached ({used}/{limit})")
450
  return
451
 
452
- if not FAL_API_KEY:
453
- await websocket.close(code=1011, reason="FAL API key not configured")
 
 
454
  return
455
 
456
- fal_key_to_use = FAL_API_KEY
457
-
458
- # Fetch temporary FAL token
459
- try:
460
- async with httpx.AsyncClient() as client:
461
- response = await client.post(
462
- "https://rest.alpha.fal.ai/tokens/",
463
- headers={
464
- "Content-Type": "application/json",
465
- "Authorization": f"Key {fal_key_to_use}"
466
- },
467
- json={
468
- "allowed_apps": ["krea-wan-14b"],
469
- "token_expiration": 5000
470
- }
471
- )
472
- response.raise_for_status()
473
- fal_token = response.json()
474
- except Exception as e:
475
- await websocket.close(code=1011, reason=f"Failed to get FAL token: {str(e)}")
476
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
477
 
478
- # Connect to FAL WebSocket
479
- fal_ws_url = f"wss://fal.run/fal-ai/krea-wan-14b/ws?fal_jwt_token={fal_token}"
480
 
481
- try:
482
  async with websockets.connect(fal_ws_url) as fal_ws:
483
  # Relay messages between client and FAL
484
  async def client_to_fal():
@@ -520,6 +520,6 @@ async def websocket_video_gen(websocket: WebSocket, user_fal_key: Optional[str]
520
  print(f"WebSocket proxy error: {e}")
521
  await websocket.close(code=1011, reason=str(e))
522
  finally:
523
- # Remove from active connections
524
  active_websockets.discard(websocket)
525
  print(f"WebSocket disconnected. Active connections: {len(active_websockets)}")
 
427
  active_websockets.add(websocket)
428
  print(f"WebSocket connected. Active connections: {len(active_websockets)}")
429
 
 
 
 
 
 
 
430
  try:
431
+ # Get user from cookie
432
+ access_token = websocket.cookies.get("access_token")
433
+ if not access_token:
434
+ await websocket.close(code=1008, reason="Not authenticated")
 
 
 
 
 
 
 
 
 
435
  return
436
 
437
+ try:
438
+ user_info = await get_user_info(access_token)
439
+ except:
440
+ await websocket.close(code=1008, reason="Invalid session")
441
  return
442
 
443
+ # If user provided their own FAL key, use it (bypass limits)
444
+ if user_fal_key:
445
+ fal_key_to_use = user_fal_key
446
+ else:
447
+ # Check if user can start session with server FAL key
448
+ can_start, used, limit = can_start_generation(user_info["username"], user_info["is_pro"])
449
+ if not can_start:
450
+ await websocket.close(code=1008, reason=f"Daily limit reached ({used}/{limit})")
451
+ return
452
+
453
+ if not FAL_API_KEY:
454
+ await websocket.close(code=1011, reason="FAL API key not configured")
455
+ return
456
+
457
+ fal_key_to_use = FAL_API_KEY
458
+
459
+ # Fetch temporary FAL token
460
+ try:
461
+ async with httpx.AsyncClient() as client:
462
+ response = await client.post(
463
+ "https://rest.alpha.fal.ai/tokens/",
464
+ headers={
465
+ "Content-Type": "application/json",
466
+ "Authorization": f"Key {fal_key_to_use}"
467
+ },
468
+ json={
469
+ "allowed_apps": ["krea-wan-14b"],
470
+ "token_expiration": 5000
471
+ }
472
+ )
473
+ response.raise_for_status()
474
+ fal_token = response.json()
475
+ except Exception as e:
476
+ await websocket.close(code=1011, reason=f"Failed to get FAL token: {str(e)}")
477
+ return
478
 
479
+ # Connect to FAL WebSocket
480
+ fal_ws_url = f"wss://fal.run/fal-ai/krea-wan-14b/ws?fal_jwt_token={fal_token}"
481
 
 
482
  async with websockets.connect(fal_ws_url) as fal_ws:
483
  # Relay messages between client and FAL
484
  async def client_to_fal():
 
520
  print(f"WebSocket proxy error: {e}")
521
  await websocket.close(code=1011, reason=str(e))
522
  finally:
523
+ # Remove from active connections - ALWAYS executes
524
  active_websockets.discard(websocket)
525
  print(f"WebSocket disconnected. Active connections: {len(active_websockets)}")