/ opencodehub / src / lib / realtime.ts
swadhinbiswas feat: finalize platform polish - discussions, gists, webhook queue, realtime, push-mirror, auth/metrics hardening · 8/28/2026
f02976d
616 lines · 17.0 KB
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/**
 * Real-time Updates Library
 * Server-Sent Events (SSE) and browser notifications for live updates
 */

import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import type Redis from "ioredis";
import { getDatabase, schema } from "@/db";
import { logger } from "@/lib/logger";
import { redis } from "@/lib/redis";

// Event types for real-time updates
export type RealtimeEventType =
    | "pr:opened"
    | "pr:updated"
    | "pr:merged"
    | "pr:closed"
    | "pr:review_requested"
    | "pr:approved"
    | "pr:changes_requested"
    | "ci:started"
    | "ci:passed"
    | "ci:failed"
    | "queue:added"
    | "queue:position_changed"
    | "queue:merging"
    | "queue:merged"
    | "notification:new"
    | "inbox:refresh";

export interface RealtimeEvent<T = unknown> {
    type: RealtimeEventType;
    timestamp: Date;
    data: T;
}

// In-memory store for active connections
interface Connection {
    userId: string;
    controller: ReadableStreamDefaultController<Uint8Array>;
    repositories: string[]; // Subscribed repository IDs
    createdAt: Date;
}

const connections = new Map<string, Connection>();

// === Cross-process fanout (Redis Pub/Sub bridge) ===
//
// SSE connections live in this process's memory only. Background processes
// (worker, runner) run in separate OS processes, so their events must be
// relayed over Redis pub/sub to reach browsers connected to the web process.
//
// - Channel: `och:realtime`
// - Envelope: JSON `{ originId, target, event }` — receivers drop messages
//   whose originId matches their own (prevents double-delivery).
// - Degradation: if Redis is unavailable, delivery silently falls back to
//   local-only with a single warn log until the connection recovers.

const REALTIME_CHANNEL = "och:realtime";
const ORIGIN_ID = crypto.randomUUID();

type RealtimeBridgeTarget =
    | { kind: "all" }
    | { kind: "user"; userId: string }
    | { kind: "repository"; repositoryId: string }
    | { kind: "connection"; connectionId: string };

interface RealtimeBridgeMessage {
    originId: string;
    target: RealtimeBridgeTarget;
    event: RealtimeEvent;
}

interface BridgeConnections {
    subscriber: Redis;
    publisher: Redis;
}

let bridge: BridgeConnections | null = null;
let bridgeInitPromise: Promise<void> | null = null;
let bridgeDegradedLogged = false;

function isRedisBridgeEnabled(): boolean {
    return !(
        process.env.SKIP_REDIS_CHECK === "1" || process.env.NODE_ENV === "test"
    );
}

function logBridgeDegraded(scope: string, error: unknown): void {
    if (bridgeDegradedLogged) return;
    bridgeDegradedLogged = true;
    logger.warn(
        "Realtime Redis bridge degraded; falling back to local-only delivery",
        { scope, error }
    );
}

function logBridgeRecovered(scope: string): void {
    if (!bridgeDegradedLogged) return;
    bridgeDegradedLogged = false;
    logger.info("Realtime Redis bridge recovered", { scope });
}

/**
 * Lazily create dedicated publisher/subscriber connections and subscribe.
 * Pub/sub requires one connection per role, so both are duplicated from the
 * shared client factory. Never throws — on failure the bridge stays disabled
 * and delivery remains local-only.
 */
async function ensureBridge(): Promise<void> {
    if (bridge || !isRedisBridgeEnabled()) return;
    if (bridgeInitPromise) return bridgeInitPromise;

    bridgeInitPromise = (async () => {
        try {
            const subscriber = redis.duplicate();
            const publisher = redis.duplicate();

            // duplicated instances do not inherit listeners; without these an
            // 'error' event would crash the process
            subscriber.on("error", (error: Error) => {
                logBridgeDegraded("subscriber", error);
            });
            publisher.on("error", (error: Error) => {
                logBridgeDegraded("publisher", error);
            });

            subscriber.on("message", (channel: string, raw: string) => {
                if (channel !== REALTIME_CHANNEL) return;
                handleBridgeMessage(raw);
            });

            await subscriber.subscribe(REALTIME_CHANNEL);
            logBridgeRecovered("subscriber");

            bridge = { subscriber, publisher };
        } catch (error) {
            logBridgeDegraded("init", error);
        } finally {
            bridgeInitPromise = null;
        }
    })();

    return bridgeInitPromise;
}

function handleBridgeMessage(raw: string): void {
    let message: RealtimeBridgeMessage;
    try {
        message = JSON.parse(raw) as RealtimeBridgeMessage;
    } catch {
        logger.warn("Dropping malformed realtime bridge message");
        return;
    }

    if (!message || message.originId === ORIGIN_ID) return;

    try {
        // timestamp round-trips as an ISO string through JSON; revive it so
        // local consumers still receive a Date
        const event: RealtimeEvent = {
            ...message.event,
            timestamp: new Date(message.event.timestamp),
        };
        deliverLocally(message.target, event);
    } catch (error) {
        logger.error("Failed to deliver bridged realtime event", { error });
    }
}

function deliverLocally(target: RealtimeBridgeTarget, event: RealtimeEvent): number {
    switch (target.kind) {
        case "user":
            return sendToUserLocal(target.userId, event);
        case "repository":
            return broadcastToRepositoryLocal(target.repositoryId, event);
        case "connection":
            return sendToConnection(target.connectionId, event) ? 1 : 0;
        case "all":
        default:
            return broadcastToAllLocal(event);
    }
}

/**
 * Fire-and-forget publish of an event to other processes via Redis.
 * Never throws and never affects local delivery; returns whether the
 * message was handed to Redis.
 */
async function publishToBridge(
    target: RealtimeBridgeTarget,
    event: RealtimeEvent
): Promise<boolean> {
    try {
        await ensureBridge();
        if (!bridge) return false;

        const payload: RealtimeBridgeMessage = { originId: ORIGIN_ID, target, event };
        const receivers = await bridge.publisher.publish(
            REALTIME_CHANNEL,
            JSON.stringify(payload)
        );
        logBridgeRecovered("publisher");
        logger.debug("Realtime event published cross-process", {
            type: event.type,
            targetKind: target.kind,
            receivers,
        });
        return true;
    } catch (error) {
        logBridgeDegraded("publish", error);
        return false;
    }
}

/**
 * Publish a realtime event from a process that holds no SSE connections
 * itself (e.g. the background worker or CI runner). The web process(s)
 * subscribed to `och:realtime` will fan the event out to connected browsers.
 */
export async function publishRealtimeEvent(
    target: RealtimeBridgeTarget,
    event: RealtimeEvent
): Promise<boolean> {
    return publishToBridge(target, event);
}

/**
 * Create a unique connection ID
 */
function generateConnectionId(): string {
    return `conn_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

/**
 * Register a new SSE connection
 */
export function registerConnection(
    userId: string,
    controller: ReadableStreamDefaultController<Uint8Array>,
    repositories: string[] = []
): string {
    // Web processes are primarily receivers of cross-process events; make sure
    // the pub/sub subscription exists as soon as the first browser connects
    void ensureBridge();

    const connectionId = generateConnectionId();

    connections.set(connectionId, {
        userId,
        controller,
        repositories,
        createdAt: new Date(),
    });

    logger.info("SSE connection registered", {
        connectionId,
        userId,
        repositories: repositories.length,
    });

    // Send initial connection confirmation
    sendToConnection(connectionId, {
        type: "inbox:refresh",
        timestamp: new Date(),
        data: { connected: true, connectionId },
    });

    return connectionId;
}

/**
 * Unregister an SSE connection
 */
export function unregisterConnection(connectionId: string): void {
    const connection = connections.get(connectionId);
    if (connection) {
        connections.delete(connectionId);
        logger.info("SSE connection unregistered", {
            connectionId,
            userId: connection.userId,
        });
    }
}

/**
 * Send an event to a specific connection
 */
export function sendToConnection(connectionId: string, event: RealtimeEvent): boolean {
    const connection = connections.get(connectionId);
    if (!connection) return false;

    try {
        const data = `data: ${JSON.stringify(event)}\n\n`;
        connection.controller.enqueue(new TextEncoder().encode(data));
        return true;
    } catch (error) {
        logger.error("Failed to send to connection", { connectionId, error });
        unregisterConnection(connectionId);
        return false;
    }
}

/**
 * Local-only delivery to a specific user's connections
 */
function sendToUserLocal(userId: string, event: RealtimeEvent): number {
    let sent = 0;

    for (const [connectionId, connection] of connections.entries()) {
        if (connection.userId === userId) {
            if (sendToConnection(connectionId, event)) {
                sent++;
            }
        }
    }

    return sent;
}

/**
 * Broadcast an event to a specific user's connections locally and to
 * subscribers in all other processes via Redis
 */
export function sendToUser(userId: string, event: RealtimeEvent): number {
    const sent = sendToUserLocal(userId, event);
    void publishToBridge({ kind: "user", userId }, event);
    return sent;
}

/**
 * Local-only delivery to all users subscribed to a repository
 */
function broadcastToRepositoryLocal(repositoryId: string, event: RealtimeEvent): number {
    let sent = 0;

    for (const [connectionId, connection] of connections.entries()) {
        if (connection.repositories.includes(repositoryId) || connection.repositories.length === 0) {
            if (sendToConnection(connectionId, event)) {
                sent++;
            }
        }
    }

    return sent;
}

/**
 * Broadcast an event to all users subscribed to a repository locally and to
 * subscribers in all other processes via Redis
 */
export function broadcastToRepository(repositoryId: string, event: RealtimeEvent): number {
    const sent = broadcastToRepositoryLocal(repositoryId, event);
    void publishToBridge({ kind: "repository", repositoryId }, event);
    return sent;
}

/**
 * Local-only delivery to all connected users
 */
function broadcastToAllLocal(event: RealtimeEvent): number {
    let sent = 0;

    for (const connectionId of connections.keys()) {
        if (sendToConnection(connectionId, event)) {
            sent++;
        }
    }

    return sent;
}

/**
 * Broadcast an event to all connected users locally and to subscribers in
 * all other processes via Redis
 */
export function broadcastToAll(event: RealtimeEvent): number {
    const sent = broadcastToAllLocal(event);
    void publishToBridge({ kind: "all" }, event);
    return sent;
}

/**
 * Get connection statistics
 */
export function getConnectionStats(): {
    totalConnections: number;
    uniqueUsers: number;
    connectionsByUser: Record<string, number>;
} {
    const userCounts: Record<string, number> = {};

    for (const connection of connections.values()) {
        userCounts[connection.userId] = (userCounts[connection.userId] || 0) + 1;
    }

    return {
        totalConnections: connections.size,
        uniqueUsers: Object.keys(userCounts).length,
        connectionsByUser: userCounts,
    };
}

/**
 * Clean up stale connections (older than specified duration)
 */
export function cleanupStaleConnections(maxAgeMs: number = 30 * 60 * 1000): number {
    const now = Date.now();
    let cleaned = 0;

    for (const [connectionId, connection] of connections.entries()) {
        if (now - connection.createdAt.getTime() > maxAgeMs) {
            try {
                connection.controller.close();
            } catch {
                // Ignore close errors
            }
            connections.delete(connectionId);
            cleaned++;
        }
    }

    if (cleaned > 0) {
        logger.info("Cleaned up stale SSE connections", { count: cleaned });
    }

    return cleaned;
}

// === Event Emitters ===

/**
 * Emit a PR event to relevant users
 */
export async function emitPREvent(
    prId: string,
    eventType: "opened" | "updated" | "merged" | "closed" | "review_requested" | "approved" | "changes_requested",
    metadata?: Record<string, unknown>
) {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    try {
        const pr = await db.query.pullRequests.findFirst({
            where: eq(schema.pullRequests.id, prId),
            with: {
                repository: true,
                author: true,
            },
        });

        if (!pr) return;

        const event: RealtimeEvent = {
            type: `pr:${eventType}` as RealtimeEventType,
            timestamp: new Date(),
            data: {
                prId: pr.id,
                prNumber: pr.number,
                title: pr.title,
                repositoryId: pr.repositoryId,
                repositoryName: pr.repository?.name,
                authorUsername: pr.author?.username,
                ...metadata,
            },
        };

        // Broadcast to repository subscribers
        broadcastToRepository(pr.repositoryId, event);

        // Also send to PR author
        if (pr.author?.id) {
            sendToUser(pr.author.id, event);
        }
    } catch (error) {
        logger.error("Failed to emit PR event", { prId, eventType, error });
    }
}

/**
 * Emit a CI event
 */
export async function emitCIEvent(
    prId: string,
    status: "started" | "passed" | "failed",
    metadata?: Record<string, unknown>
) {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    try {
        const pr = await db.query.pullRequests.findFirst({
            where: eq(schema.pullRequests.id, prId),
            with: { author: true },
        });

        if (!pr) return;

        const event: RealtimeEvent = {
            type: `ci:${status}` as RealtimeEventType,
            timestamp: new Date(),
            data: {
                prId: pr.id,
                prNumber: pr.number,
                repositoryId: pr.repositoryId,
                ...metadata,
            },
        };

        broadcastToRepository(pr.repositoryId, event);

        if (pr.author?.id) {
            sendToUser(pr.author.id, event);
        }
    } catch (error) {
        logger.error("Failed to emit CI event", { prId, status, error });
    }
}

/**
 * Emit a merge queue event
 */
export async function emitQueueEvent(
    repositoryId: string,
    eventType: "added" | "position_changed" | "merging" | "merged",
    prId: string,
    metadata?: Record<string, unknown>
) {
    const event: RealtimeEvent = {
        type: `queue:${eventType}` as RealtimeEventType,
        timestamp: new Date(),
        data: {
            repositoryId,
            prId,
            ...metadata,
        },
    };

    broadcastToRepository(repositoryId, event);
}

/**
 * Emit a notification event
 */
export function emitNotification(
    userId: string,
    notification: {
        id: string;
        type: string;
        title: string;
        body?: string;
        url?: string;
    }
) {
    const event: RealtimeEvent = {
        type: "notification:new",
        timestamp: new Date(),
        data: notification,
    };

    sendToUser(userId, event);
}

// === Helper for creating SSE response ===

/**
 * Create an SSE-compatible Response
 */
export function createSSEResponse(
    userId: string,
    repositories: string[] = []
): Response {
    let connectionId: string;
    let heartbeatInterval: ReturnType<typeof setInterval> | null = null;

    const stream = new ReadableStream<Uint8Array>({
        start(controller) {
            connectionId = registerConnection(userId, controller, repositories);

            // Send heartbeat every 30 seconds to keep connection alive
            heartbeatInterval = setInterval(() => {
                try {
                    controller.enqueue(new TextEncoder().encode(": heartbeat\n\n"));
                } catch {
                    if (heartbeatInterval) clearInterval(heartbeatInterval);
                }
            }, 30000);
        },
        cancel() {
            // Clear heartbeat interval to prevent memory leak
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
                heartbeatInterval = null;
            }
            if (connectionId) {
                unregisterConnection(connectionId);
            }
        },
    });

    return new Response(stream, {
        headers: {
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no", // Disable Nginx buffering
        },
    });
}

// Start cleanup interval (every 5 minutes)
if (typeof setInterval !== "undefined") {
    setInterval(() => {
        cleanupStaleConnections();
    }, 5 * 60 * 1000);
}