Spaces:
Running

File size: 2,057 Bytes
6f5f15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { randomUUID } from 'node:crypto';
import type { Hono } from 'hono';
import { streamSSE } from 'hono/streaming';
import type * as T from '../../shared/api-types.js';
import type { RoomRegistryApi } from '../contracts.js';
import { resolveUser } from './userParam.js';

const HEARTBEAT_INTERVAL_MS = 15_000;

export function mountFeedRoute(app: Hono, deps: { rooms: RoomRegistryApi }): void {
  app.get('/api/feed', (c) => {
    const user = resolveUser(c.req.raw);
    const tabId = c.req.query('tab')?.trim() || randomUUID();
    const userAgent = c.req.header('user-agent');
    const room = deps.rooms.get(user);

    c.header('Cache-Control', 'no-cache, no-transform');
    c.header('X-Accel-Buffering', 'no');

    return streamSSE(c, async (stream) => {
      let closed = false;
      let writeChain = Promise.resolve();

      const enqueue = (fn: () => Promise<void>): void => {
        if (closed) return;
        writeChain = writeChain.then(async () => {
          if (closed) return;
          try {
            await fn();
          } catch {
            closed = true;
          }
        });
      };

      const sendMessage = (msg: T.FeedMessage): void => {
        enqueue(() => stream.writeSSE({ data: JSON.stringify(msg) }));
      };

      const removeTab = room.camera.addTab(tabId, sendMessage, userAgent);
      const unsubFeed = room.changes.onFeed(sendMessage);

      // Send hello + immediate snapshot
      sendMessage({
        type: 'hello',
        tabId,
        serverTime: new Date().toISOString(),
      });
      sendMessage({
        type: 'state',
        state: room.snapshot(),
      });

      const heartbeat = setInterval(() => {
        enqueue(async () => {
          await stream.write(': ping\n\n');
        });
      }, HEARTBEAT_INTERVAL_MS);
      heartbeat.unref?.();

      await new Promise<void>((resolve) => {
        stream.onAbort(() => {
          resolve();
        });
      });

      closed = true;
      clearInterval(heartbeat);
      unsubFeed();
      removeTab();
    });
  });
}