| 1 | import { env } from "cloudflare:workers"; |
| 2 | |
| 3 | import { NOTIFY_SEED_HEADER, NOTIFY_VIEWER_HEADER, type FeedSeed, type User } from "@g1t/contracts"; |
| 4 | |
| 5 | import type { Route } from "./+types/live"; |
| 6 | import { chat, inbox } from "../../lib/services.server"; |
| 7 | import { getViewer, roleIn } from "../../lib/session.server"; |
| 8 | |
| 9 | /** The longest the counts read for a new socket hold it up. */ |
| 10 | const SEED_WAIT_MS = 800; |
| 11 | |
| 12 | function within<T>(work: Promise<T>): Promise<T | null> { |
| 13 | const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), SEED_WAIT_MS)); |
| 14 | return Promise.race([work.catch(() => null), timeout]); |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * The counts a new socket starts from, read from chat and the inbox now: |
| 19 | * the feed takes them as the truth for that workspace, then moves them as |
| 20 | * messages and reads arrive. Whatever is slow is left out, not waited for. |
| 21 | */ |
| 22 | async function seedFor(viewer: User, workspace: string | null): Promise<FeedSeed> { |
| 23 | const [sidebar, counts] = await Promise.all([ |
| 24 | workspace ? within(chat.sidebar(workspace, viewer)) : Promise.resolve(null), |
| 25 | within(inbox.counts(viewer.username)), |
| 26 | ]); |
| 27 | return { |
| 28 | workspace, |
| 29 | per_channel: sidebar?.ok |
| 30 | ? sidebar.value.entries.map((e) => ({ channel_id: e.channel.id, unread: e.unread, mentions: e.mentions, muted: e.muted })) |
| 31 | : null, |
| 32 | inbox_unread: counts ? counts.unread : null, |
| 33 | }; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * The signed-in person's feed: `wss://<site>/-/live?workspace=<slug>`, open |
| 38 | * on every page. The site checks the session and that the page asking is |
| 39 | * its own, reads the workspace's counts, and hands the upgrade to the |
| 40 | * notify service, which keeps the socket (one Durable Object per person, |
| 41 | * hibernating while nothing happens). |
| 42 | */ |
| 43 | export async function loader({ context, request }: Route.LoaderArgs) { |
| 44 | const viewer = getViewer(context); |
| 45 | if (!viewer) return new Response("Sign in first.", { status: 401 }); |
| 46 | if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") { |
| 47 | return new Response("This address takes a WebSocket.", { status: 426, headers: { upgrade: "websocket" } }); |
| 48 | } |
| 49 | // Only the site's own pages may open it: a page elsewhere carries the cookie too. |
| 50 | const origin = request.headers.get("origin"); |
| 51 | if (origin && origin !== new URL(request.url).origin) return new Response("Cross-origin socket refused", { status: 403 }); |
| 52 | if (!env.NOTIFY) return new Response("Notifications are not set up here.", { status: 503 }); |
| 53 | const slug = (new URL(request.url).searchParams.get("workspace") ?? "").toLowerCase(); |
| 54 | const seed = await seedFor(viewer, slug && roleIn(viewer, slug) ? slug : null); |
| 55 | const headers = new Headers(request.headers); |
| 56 | // Neither the session nor anything else of the browser's goes on. |
| 57 | headers.delete("cookie"); |
| 58 | headers.set(NOTIFY_VIEWER_HEADER, JSON.stringify({ id: viewer.id, username: viewer.username })); |
| 59 | headers.set(NOTIFY_SEED_HEADER, JSON.stringify(seed)); |
| 60 | try { |
| 61 | return await env.NOTIFY.fetch(new Request("https://notify/live", { method: "GET", headers })); |
| 62 | } catch (error) { |
| 63 | console.error("notify: the live socket could not be handed over", error); |
| 64 | return new Response("Notifications didn't answer.", { status: 503 }); |
| 65 | } |
| 66 | } |