feat: implement kanban real-time sync and fix workload cache
## Kanban Real-time Sync (NEW-002)
- Backend:
- WebSocket endpoint: /ws/projects/{project_id}
- Project room management in ConnectionManager
- Redis Pub/Sub: project:{project_id}:tasks channel
- Task CRUD event publishing (5 event types)
- Redis connection retry with exponential backoff
- Race condition fix in broadcast_to_project
- Frontend:
- ProjectSyncContext for WebSocket management
- Reconnection with exponential backoff (max 5 attempts)
- Multi-tab event deduplication via event_id
- Live/Offline connection indicator
- Optimistic updates with rollback
- Spec:
- collaboration spec: +1 requirement (Project Real-time Sync)
- 7 new scenarios for real-time sync
## Workload Cache Fix (NEW-001)
- Added cache invalidation to all task endpoints:
- create_task, update_task, update_task_status
- delete_task, restore_task, assign_task
- Extended to clear heatmap cache as well
## OpenSpec Archive
- 2026-01-05-add-kanban-realtime-sync
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,17 +1,23 @@
|
||||
import json
|
||||
import asyncio
|
||||
from typing import Dict, Set, Optional
|
||||
import logging
|
||||
from typing import Dict, Set, Optional, Tuple
|
||||
from fastapi import WebSocket
|
||||
from app.core.redis import get_redis_sync
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Manager for WebSocket connections."""
|
||||
|
||||
def __init__(self):
|
||||
# user_id -> set of WebSocket connections
|
||||
# user_id -> set of WebSocket connections (for notifications)
|
||||
self.active_connections: Dict[str, Set[WebSocket]] = {}
|
||||
# project_id -> set of (user_id, WebSocket) tuples (for project sync)
|
||||
self.project_connections: Dict[str, Set[Tuple[str, WebSocket]]] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self._project_lock = asyncio.Lock()
|
||||
|
||||
async def connect(self, websocket: WebSocket, user_id: str):
|
||||
"""Accept and track a new WebSocket connection."""
|
||||
@@ -52,6 +58,93 @@ class ConnectionManager:
|
||||
"""Check if a user has any active connections."""
|
||||
return user_id in self.active_connections and len(self.active_connections[user_id]) > 0
|
||||
|
||||
# Project room management methods
|
||||
|
||||
async def join_project(self, websocket: WebSocket, user_id: str, project_id: str):
|
||||
"""
|
||||
Add user to a project room for real-time task sync.
|
||||
|
||||
Args:
|
||||
websocket: The WebSocket connection
|
||||
user_id: The user's ID
|
||||
project_id: The project to join
|
||||
"""
|
||||
async with self._project_lock:
|
||||
if project_id not in self.project_connections:
|
||||
self.project_connections[project_id] = set()
|
||||
self.project_connections[project_id].add((user_id, websocket))
|
||||
logger.debug(f"User {user_id} joined project room {project_id}")
|
||||
|
||||
async def leave_project(self, websocket: WebSocket, user_id: str, project_id: str):
|
||||
"""
|
||||
Remove user from a project room.
|
||||
|
||||
Args:
|
||||
websocket: The WebSocket connection
|
||||
user_id: The user's ID
|
||||
project_id: The project to leave
|
||||
"""
|
||||
async with self._project_lock:
|
||||
if project_id in self.project_connections:
|
||||
self.project_connections[project_id].discard((user_id, websocket))
|
||||
if not self.project_connections[project_id]:
|
||||
del self.project_connections[project_id]
|
||||
logger.debug(f"User {user_id} left project room {project_id}")
|
||||
|
||||
async def broadcast_to_project(
|
||||
self,
|
||||
project_id: str,
|
||||
message: dict,
|
||||
exclude_user_id: Optional[str] = None
|
||||
):
|
||||
"""
|
||||
Broadcast message to all users in a project room.
|
||||
|
||||
Args:
|
||||
project_id: The project room to broadcast to
|
||||
message: The message to send
|
||||
exclude_user_id: Optional user ID to exclude from broadcast (e.g., the sender)
|
||||
"""
|
||||
# Create snapshot while holding lock to prevent race condition
|
||||
async with self._project_lock:
|
||||
if project_id not in self.project_connections:
|
||||
return
|
||||
connections_snapshot = list(self.project_connections[project_id])
|
||||
|
||||
disconnected = set()
|
||||
for user_id, websocket in connections_snapshot:
|
||||
# Skip excluded user (sender)
|
||||
if exclude_user_id and user_id == exclude_user_id:
|
||||
continue
|
||||
|
||||
try:
|
||||
await websocket.send_json(message)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to send message to user {user_id} in project {project_id}: {e}")
|
||||
disconnected.add((user_id, websocket))
|
||||
|
||||
# Clean up disconnected connections
|
||||
if disconnected:
|
||||
async with self._project_lock:
|
||||
for conn in disconnected:
|
||||
if project_id in self.project_connections:
|
||||
self.project_connections[project_id].discard(conn)
|
||||
if not self.project_connections[project_id]:
|
||||
del self.project_connections[project_id]
|
||||
|
||||
def get_project_user_count(self, project_id: str) -> int:
|
||||
"""Get the number of unique users in a project room."""
|
||||
if project_id not in self.project_connections:
|
||||
return 0
|
||||
unique_users = set(user_id for user_id, _ in self.project_connections[project_id])
|
||||
return len(unique_users)
|
||||
|
||||
def is_user_in_project(self, user_id: str, project_id: str) -> bool:
|
||||
"""Check if a user has any active connections to a project room."""
|
||||
if project_id not in self.project_connections:
|
||||
return False
|
||||
return any(uid == user_id for uid, _ in self.project_connections[project_id])
|
||||
|
||||
|
||||
# Global connection manager instance
|
||||
manager = ConnectionManager()
|
||||
|
||||
Reference in New Issue
Block a user