Spaces:
Paused

File size: 17,552 Bytes
5eb4857
356a201
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
c65ce91
5eb4857
356a201
 
5eb4857
4a6adfb
 
5eb4857
 
356a201
 
5eb4857
4a6adfb
 
 
 
 
 
 
 
 
 
356a201
 
 
 
 
 
 
 
5eb4857
 
6ba1c48
356a201
5eb4857
356a201
 
5eb4857
 
356a201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5df217f
 
 
 
 
356a201
 
 
5df217f
 
 
 
 
 
 
 
356a201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b34dce7
5df217f
 
 
 
356a201
 
 
 
 
 
 
5df217f
356a201
b34dce7
356a201
 
 
5df217f
356a201
 
 
 
5df217f
 
 
 
 
 
356a201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9eaba40
 
 
356a201
 
9eaba40
356a201
 
9eaba40
356a201
 
 
9eaba40
356a201
 
9eaba40
356a201
 
 
 
 
 
9eaba40
356a201
9eaba40
 
356a201
 
 
9eaba40
356a201
 
9eaba40
356a201
 
9eaba40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356a201
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
6ba1c48
 
 
 
356a201
6ba1c48
 
 
 
356a201
6ba1c48
356a201
 
 
 
5eb4857
356a201
 
 
 
 
 
 
 
6ba1c48
 
 
9eaba40
 
356a201
6ba1c48
356a201
6ba1c48
356a201
 
6ba1c48
 
356a201
6ba1c48
356a201
 
 
9eaba40
 
5eb4857
 
 
6ba1c48
 
 
 
5eb4857
6ba1c48
 
 
 
9eaba40
 
5eb4857
356a201
 
c65ce91
 
356a201
 
c65ce91
356a201
c65ce91
 
 
 
 
 
356a201
c65ce91
 
356a201
 
 
 
c65ce91
356a201
 
 
 
 
c65ce91
356a201
 
 
 
 
 
 
 
5eb4857
e440c64
356a201
 
 
1049d57
356a201
 
 
 
 
 
 
 
 
 
 
 
 
e440c64
 
356a201
 
 
 
c65ce91
356a201
 
 
 
 
 
 
 
e440c64
5eb4857
356a201
 
 
c65ce91
356a201
 
 
 
 
 
 
 
 
5eb4857
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"""
WebSocket Connection Manager with Redis Pub/Sub fan-out.

Each API worker process tracks its own live WebSocket objects in memory.
When code calls broadcast_to_workspace / send_to_user / etc., the message
is published to a Redis channel.  A background subscriber task running inside
EVERY worker process receives the published message and delivers it to
whichever WebSocket objects that process happens to hold.

This means one broadcast call reaches every connected client regardless of
which worker process they are connected to β€” a prerequisite for horizontal
scaling beyond a single process.

Fallback: if Redis is unavailable, all four broadcast methods fall back to
direct local delivery so single-process deployments are unaffected.
"""

import asyncio
import json
import logging
from typing import Any, Dict, List, Optional, Set
from uuid import UUID
from datetime import datetime
from enum import Enum
from fastapi import WebSocket

logger = logging.getLogger(__name__)


class NexusJSONEncoder(json.JSONEncoder):
    """Custom encoder to handle Nexus-specific types in WebSockets."""
    def default(self, obj):
        if isinstance(obj, Enum):
            return obj.value
        if isinstance(obj, (UUID, datetime)):
            return str(obj)
        return super().default(obj)


# ── Redis channel naming ──────────────────────────────────────────────────── #
# nexus:ws:workspace:{uuid}
# nexus:ws:user:{uuid}
# nexus:ws:role:{workspace_uuid}:{role_str}
# nexus:ws:ticket:{uuid}
_PATTERN = "nexus:ws:*"


class ConnectionManager:
    def __init__(self):
        self.lock = asyncio.Lock()
        # In-process connection maps (per-worker only)
        self.active_connections: Dict[UUID, Set[WebSocket]] = {}
        self.user_connections:   Dict[UUID, List[WebSocket]] = {}
        self.role_connections:   Dict[tuple, Set[WebSocket]] = {}
        self.ticket_connections: Dict[UUID, Set[WebSocket]] = {}

        # Redis pub/sub
        self._subscriber_task: Optional[asyncio.Task] = None
        self._pub_redis = None          # lazy-init publish client
        self._redis_url: Optional[str]  = None

    # ── Lifecycle ──────────────────────────────────────────────────────────── #

    async def start_pubsub(self, redis_url: str):
        """
        Called once per worker process at startup.
        Launches the background subscriber that delivers cross-process messages
        to WebSocket connections held by this process.
        """
        self._redis_url = redis_url
        self._subscriber_task = asyncio.create_task(
            self._subscriber_loop(redis_url),
            name="nexus_ws_pubsub_subscriber",
        )
        logger.info("WebSocket Redis pub/sub subscriber started.")

    async def stop_pubsub(self):
        """Cancel subscriber and close publish client on worker shutdown."""
        if self._subscriber_task and not self._subscriber_task.done():
            self._subscriber_task.cancel()
            try:
                await self._subscriber_task
            except asyncio.CancelledError:
                pass
        if self._pub_redis:
            try:
                await self._pub_redis.aclose()
            except Exception:
                pass

    # ── Internal: publish ─────────────────────────────────────────────────── #

    async def _get_pub_redis(self):
        """
        Lazy-initialise a dedicated async Redis client for publishing.
        Uses the same local Redis URL as the subscriber so both publish and
        subscribe traffic stays off cloud/billed Redis instances.
        """
        if self._pub_redis is None:
            import redis.asyncio as aioredis
            url = self._redis_url or "redis://localhost:6379"
            self._pub_redis = aioredis.from_url(
                url,
                encoding="utf-8",
                decode_responses=True,
                socket_connect_timeout=5.0,
                socket_timeout=5.0,
                socket_keepalive=True,
            )
        return self._pub_redis

    async def _publish(self, channel: str, message: Any) -> bool:
        """
        Publish a serialised message to a Redis pub/sub channel.
        Returns True on success.  On failure callers use local fallback.
        """
        try:
            payload = json.dumps(message, cls=NexusJSONEncoder)
            r = await self._get_pub_redis()
            await r.publish(channel, payload)
            return True
        except Exception as exc:
            logger.warning(f"WebSocket Redis publish failed on {channel}: {exc}")
            return False

    # ── Internal: subscriber loop ─────────────────────────────────────────── #

    async def _subscriber_loop(self, redis_url: str):
        """
        Long-lived background task.  Subscribes to nexus:ws:* and calls
        _dispatch_local() for every received message so this process's
        WebSocket connections receive cross-process broadcasts.

        IMPORTANT: redis_url must point at the LOCAL Redis, not a cloud/serverless
        Redis (e.g. Upstash).  Cloud providers impose idle-connection timeouts and
        bill per command β€” both incompatible with a persistent pub/sub listener.
        The local Redis (started by run_prod.sh) has no such limits.
        """
        import redis.asyncio as aioredis

        kwargs: dict = {
            "encoding": "utf-8",
            "decode_responses": True,
            "socket_connect_timeout": 5.0,
            "socket_keepalive": True,
        }

        while True:
            sub_redis = None
            try:
                sub_redis = aioredis.from_url(redis_url, **kwargs)
                pubsub    = sub_redis.pubsub()
                await pubsub.psubscribe(_PATTERN)
                logger.info("WebSocket subscriber: listening on nexus:ws:*")

                async for message in pubsub.listen():
                    if message["type"] != "pmessage":
                        continue
                    await self._dispatch_local(
                        channel=message["channel"],
                        payload=message["data"],
                    )
            except asyncio.CancelledError:
                logger.info("WebSocket pub/sub subscriber cancelled.")
                break
            except Exception as exc:
                logger.warning(f"WebSocket subscriber error β€” reconnecting in 2 s: {exc}")
                await asyncio.sleep(2)
            finally:
                if sub_redis:
                    try:
                        await sub_redis.aclose()
                    except Exception:
                        pass

    async def _dispatch_local(self, channel: str, payload: str):
        """
        Route a Redis pub/sub message to local WebSocket connections for
        the appropriate target derived from the channel name.

        Channel formats:
            nexus:ws:workspace:{uuid}
            nexus:ws:user:{uuid}
            nexus:ws:role:{ws_uuid}:{role}
            nexus:ws:ticket:{uuid}
        """
        try:
            # Strip the fixed prefix "nexus:ws:" β†’ split the remainder
            # parts example: ["workspace", "550e8400-e29b-..."]
            parts = channel.split(":", 3)   # ["nexus", "ws", type, rest]
            if len(parts) < 4:
                return
            target_type, rest = parts[2], parts[3]

            connections: list = []
            map_key = None
            map_ref = None

            if target_type == "workspace":
                ws_id = UUID(rest)
                map_key = ws_id
                async with self.lock:
                    connections = list(self.active_connections.get(ws_id, set()))
                map_ref = self.active_connections

            elif target_type == "user":
                user_id = UUID(rest)
                map_key = user_id
                async with self.lock:
                    connections = list(self.user_connections.get(user_id, []))
                map_ref = self.user_connections

            elif target_type == "role":
                # rest = "{ws_uuid}:{role}"
                role_parts = rest.split(":", 1)
                if len(role_parts) == 2:
                    ws_id, role = UUID(role_parts[0]), role_parts[1]
                    map_key = (ws_id, role)
                    async with self.lock:
                        connections = list(self.role_connections.get(map_key, set()))
                    map_ref = self.role_connections

            elif target_type == "ticket":
                ticket_id = UUID(rest)
                map_key = ticket_id
                async with self.lock:
                    connections = list(self.ticket_connections.get(ticket_id, set()))
                map_ref = self.ticket_connections

            if connections:
                payload_str = payload if isinstance(payload, str) else payload
                dead = await self._send_all(connections, payload_str)
                if dead and map_ref is not None and map_key is not None:
                    async with self.lock:
                        bucket = map_ref.get(map_key)
                        if bucket is not None:
                            if isinstance(bucket, set):
                                bucket -= dead
                                if not bucket:
                                    map_ref.pop(map_key, None)
                            elif isinstance(bucket, list):
                                for d in dead:
                                    try:
                                        bucket.remove(d)
                                    except ValueError:
                                        pass
                                if not bucket:
                                    map_ref.pop(map_key, None)
        except Exception as exc:
            logger.debug(f"WebSocket dispatch error on channel {channel}: {exc}")

    # ── Connection registration ───────────────────────────────────────────── #

    async def connect(
        self,
        websocket: WebSocket,
        workspace_id: UUID,
        user_id: Optional[UUID] = None,
        role: Optional[str] = None,
    ):
        """Accept a WebSocket connection and register it in this process's maps."""
        await websocket.accept()
        async with self.lock:
            if workspace_id not in self.active_connections:
                self.active_connections[workspace_id] = set()
            self.active_connections[workspace_id].add(websocket)

            if user_id:
                if user_id not in self.user_connections:
                    self.user_connections[user_id] = []
                self.user_connections[user_id].append(websocket)

            if role:
                key = (workspace_id, role.lower())
                if key not in self.role_connections:
                    self.role_connections[key] = set()
                self.role_connections[key].add(websocket)

    async def disconnect(
        self,
        websocket: WebSocket,
        workspace_id: UUID,
        user_id: Optional[UUID] = None,
        role: Optional[str] = None,
    ):
        """Remove a WebSocket connection from this process's maps."""
        async with self.lock:
            if workspace_id in self.active_connections:
                self.active_connections[workspace_id].discard(websocket)
                if not self.active_connections[workspace_id]:
                    del self.active_connections[workspace_id]

            if user_id and user_id in self.user_connections:
                try:
                    self.user_connections[user_id].remove(websocket)
                except ValueError:
                    pass
                if not self.user_connections[user_id]:
                    del self.user_connections[user_id]

            if role:
                key = (workspace_id, role.lower())
                if key in self.role_connections:
                    self.role_connections[key].discard(websocket)
                    if not self.role_connections[key]:
                        del self.role_connections[key]

    async def connect_ticket(self, websocket: WebSocket, ticket_id: UUID):
        await websocket.accept()
        async with self.lock:
            if ticket_id not in self.ticket_connections:
                self.ticket_connections[ticket_id] = set()
            self.ticket_connections[ticket_id].add(websocket)

    async def disconnect_ticket(self, websocket: WebSocket, ticket_id: UUID):
        async with self.lock:
            if ticket_id in self.ticket_connections:
                self.ticket_connections[ticket_id].discard(websocket)
                if not self.ticket_connections[ticket_id]:
                    del self.ticket_connections[ticket_id]

    # ── Internal: safe send ───────────────────────────────────────────────── #

    async def _send_all(self, connections: list, payload: str) -> set:
        """
        Send payload to all given connections concurrently.
        Returns the set of dead connections so callers can prune them.
        """
        async def _try(ws: WebSocket):
            try:
                await ws.send_text(payload)
                return None
            except Exception:
                return ws

        results = await asyncio.gather(*[_try(c) for c in connections])
        return {r for r in results if r is not None}

    # ── Public broadcast API ──────────────────────────────────────────────── #
    # Each method publishes to Redis so ALL worker processes receive the
    # message via their subscriber loop.  If Redis is unavailable the method
    # falls back to local delivery only (graceful degradation).

    async def broadcast_to_workspace(self, workspace_id: UUID, message: Any):
        """Fan-out to every connection in a workspace across all worker processes."""
        channel = f"nexus:ws:workspace:{workspace_id}"
        if not await self._publish(channel, message):
            # Redis down β€” deliver locally only
            async with self.lock:
                conns = list(self.active_connections.get(workspace_id, set()))
            if conns:
                payload = json.dumps(message, cls=NexusJSONEncoder)
                dead = await self._send_all(conns, payload)
                if dead:
                    async with self.lock:
                        for c in dead:
                            self.active_connections[workspace_id].discard(c)

    async def send_to_user(self, user_id: UUID, message: Any):
        """Fan-out to all sessions of a single user across all worker processes."""
        channel = f"nexus:ws:user:{user_id}"
        if not await self._publish(channel, message):
            async with self.lock:
                conns = list(self.user_connections.get(user_id, []))
            if conns:
                payload = json.dumps(message, cls=NexusJSONEncoder)
                dead = await self._send_all(conns, payload)
                if dead:
                    async with self.lock:
                        for c in dead:
                            try:
                                self.user_connections[user_id].remove(c)
                            except ValueError:
                                pass
                        if not self.user_connections.get(user_id):
                            self.user_connections.pop(user_id, None)

    async def broadcast_to_role(self, workspace_id: UUID, role: str, message: Any):
        """Fan-out to all users with a given role in a workspace."""
        channel = f"nexus:ws:role:{workspace_id}:{role.lower()}"
        if not await self._publish(channel, message):
            key = (workspace_id, role.lower())
            async with self.lock:
                conns = list(self.role_connections.get(key, set()))
            if conns:
                payload = json.dumps(message, cls=NexusJSONEncoder)
                dead = await self._send_all(conns, payload)
                if dead:
                    async with self.lock:
                        for c in dead:
                            self.role_connections[key].discard(c)

    async def broadcast_to_ticket(self, ticket_id: UUID, message: Any):
        """Fan-out to all subscribers of a ticket thread."""
        channel = f"nexus:ws:ticket:{ticket_id}"
        if not await self._publish(channel, message):
            async with self.lock:
                conns = list(self.ticket_connections.get(ticket_id, set()))
            if conns:
                payload = json.dumps(message, cls=NexusJSONEncoder)
                dead = await self._send_all(conns, payload)
                if dead:
                    async with self.lock:
                        for c in dead:
                            self.ticket_connections[ticket_id].discard(c)


manager = ConnectionManager()