Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
219 linesCodeBlameRaw
1/**
2 * The notify service: live notifications, unread counts, and push to
3 * browsers (Web Push) and to the phone app (through Expo, src/expopush.ts).
4 * One feed per person (src/feed.ts).
5 *
6 * Reached through service bindings only: `POST /rpc/<method>` with
7 * snake_case bodies (`notifyClient` in @g1t/contracts), and `GET /live`,
8 * the person's feed socket, which the site forwards after checking the
9 * session (NOTIFY_VIEWER_HEADER), with the counts it read (NOTIFY_SEED_HEADER).
10 *
11 * Who sends what:
12 * - chat: `deliver`, for every message (counts for each person in the
13 * conversation, a notification for those it is for) and every read;
14 * `forget_conversation`, when someone clears their direct message with
15 * @g1t (src/forget.ts);
16 * - events: `notify`, for every inbox item, and `set_inbox`, the count after
17 * items arrive or are marked, naming the person by username;
18 * - the site: `subscribe`, `unsubscribe`, `status`, `set_preferences`,
19 * `test`, `presence` and `set_presence`, for the person signed in;
20 * `register_device` and `unregister_device`, for the phone app they
21 * signed in to (through `/-/notify`); and
22 * `last_visit` and `mark_visit`, when they were last on a workspace's
23 * Home page (src/visits.ts);
24 * - the site: `workspace_presence`, how a workspace's people
25 * show now (away, in Do Not Disturb, offline, and their statuses);
26 * - integrations, later: `set_presence` with a status of `source`
27 * `calendar` or `integration`, for the person they act for;
28 * - events and actions: `repo_changed`, what changed in repositories,
29 * told to whoever watches their pages; and the site `watch_repo`, for a
30 * tab on a repository page whose person it checked may read it.
31 *
32 * Presence: each feed works out its person's from their tabs and tells
33 * one room per workspace (src/room.ts), which tells everyone there who is
34 * online. See docs.g1t.sh/guides/chat/, "Presence and status".
35 *
36 * Live repository pages: one topic per repository (src/topic.ts) keeps
37 * who is watching it, and hands each change to their feeds. See
38 * docs.g1t.sh/guides/notifications/, "Pages that update live".
39 */
40import {
41 NOTIFY_VIEWER_HEADER,
42 identityClient,
43 type FeedDelivery,
44 type ServiceBinding,
45 type Viewer,
46} from "@g1t/contracts";
47
48import { FEED_USERNAME_HEADER, FEED_USER_ID_HEADER, Feed, type FeedEnv } from "./feed.ts";
49import { cleanChannelId } from "./forget.ts";
50import { onlyPeople } from "./presence.ts";
51import { visitWorkspace } from "./visits.ts";
52import { byRepo, cleanRepoId, cleanRepoPath } from "./watch.ts";
53
54export { Feed } from "./feed.ts";
55export { Room } from "./room.ts";
56export { Topic } from "./topic.ts";
57
58type Env = FeedEnv & {
59 IDENTITY: ServiceBinding;
60 FEEDS: DurableObjectNamespace<Feed>;
61};
62
63function feed(env: Env, userId: string) {
64 return env.FEEDS.get(env.FEEDS.idFromName(userId));
65}
66
67/** A user id from the arguments, or one looked up by username. */
68async function userIdOf(env: Env, given: { user_id?: unknown; username?: unknown; target?: unknown }): Promise<string | null> {
69 // Who it's for, at the top level or under `target`.
70 const target = given.target && typeof given.target === "object" ? (given.target as { user_id?: unknown; username?: unknown }) : null;
71 const args = { user_id: given.user_id ?? target?.user_id, username: given.username ?? target?.username };
72 if (typeof args.user_id === "string" && args.user_id) return args.user_id;
73 if (typeof args.username !== "string" || !args.username) return null;
74 const user = await identityClient(env.IDENTITY)
75 .userByUsername(args.username)
76 .catch(() => null);
77 return user?.id ?? null;
78}
79
80/** The most deliveries in one call; chat sends one per person in the conversation. */
81const MAX_DELIVERIES = 1000;
82
83async function answer(env: Env, method: string, args: any): Promise<Response> {
84 if (method === "purge_personal_data") {
85 if (typeof args?.id !== "string" || !args.id) return Response.json({ ok: false }, { status: 400 });
86 if (args.kind === "user") return Response.json(await feed(env, args.id).erase(args.id));
87 if (args.kind !== "workspace" || typeof args.slug !== "string" || !args.slug) return Response.json({ ok: false }, { status: 400 });
88 // Every slug it went by, and everyone identity knew as a member when it
89 // was purged, besides those its presence rooms know: their feeds keep
90 // notifications, counts and visits under the slug.
91 const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((v): v is string => typeof v === "string" && v.length > 0) : []);
92 const slugs = [...new Set([args.slug, ...strings(args.old_slugs)].map((slug) => slug.toLowerCase()))];
93 const members = strings(args.members);
94 for (const slug of slugs) {
95 const room = env.ROOMS?.get(env.ROOMS.idFromName(slug));
96 const people = room ? await room.eraseMembers() : [];
97 const everyone = [...new Set([...people, ...members])];
98 for (let i = 0; i < everyone.length; i += 20) {
99 await Promise.all(everyone.slice(i, i + 20).map((userId) => feed(env, userId).eraseWorkspace(slug)));
100 }
101 // Only once their feeds are cleared, so a failure leaves them listed for the retry.
102 if (room) for (const userId of people) await room.dropPerson(userId);
103 }
104 return Response.json({ ok: true });
105 }
106 if (method === "workspace_presence") {
107 // For services: how a workspace's people show now, as its room keeps them.
108 const slug = typeof args?.workspace === "string" ? args.workspace.trim().toLowerCase() : "";
109 if (!slug || !env.ROOMS) return Response.json([]);
110 const everyone = await env.ROOMS.get(env.ROOMS.idFromName(slug)).people();
111 return Response.json(onlyPeople(everyone, Array.isArray(args.user_ids) ? args.user_ids : null));
112 }
113 if (method === "repo_changed") {
114 // For services: each repository's changes to its topic, which tells its watchers.
115 const topics = env.TOPICS;
116 if (!topics) return Response.json({ ok: true });
117 const grouped = byRepo(args?.changes);
118 const results = await Promise.allSettled([...grouped].map(([id, changes]) => topics.get(topics.idFromName(id)).changed(id, changes)));
119 for (const result of results) if (result.status === "rejected") console.error("notify: a repository's change was not told", result.reason);
120 return Response.json({ ok: true });
121 }
122 if (method === "deliver") {
123 const items = (Array.isArray(args?.items) ? args.items : []).slice(0, MAX_DELIVERIES) as FeedDelivery[];
124 const byUser = new Map<string, FeedDelivery[]>();
125 for (const item of items) {
126 if (typeof item?.user_id !== "string" || !item.user_id) continue;
127 byUser.set(item.user_id, [...(byUser.get(item.user_id) ?? []), item]);
128 }
129 const results = await Promise.allSettled([...byUser].map(([id, mine]) => feed(env, id).deliver(mine)));
130 for (const result of results) if (result.status === "rejected") console.error("notify: a delivery failed", result.reason);
131 return Response.json({ ok: true });
132 }
133 const userId = await userIdOf(env, args ?? {});
134 if (!userId) return Response.json({ ok: false });
135 const stub = feed(env, userId);
136 switch (method) {
137 case "notify":
138 return Response.json(await stub.notify(args.notification));
139 case "set_inbox":
140 return Response.json(await stub.setInbox(Number(args.unread)));
141 case "subscribe":
142 return Response.json(await stub.subscribe(args.subscription, typeof args.user_agent === "string" ? args.user_agent : null));
143 case "unsubscribe":
144 return Response.json(await stub.unsubscribe(String(args.endpoint ?? "")));
145 case "register_device":
146 return Response.json(await stub.registerDevice(args.device));
147 case "unregister_device":
148 return Response.json(await stub.unregisterDevice(String(args.token ?? "")));
149 case "status":
150 return Response.json(await stub.status(typeof args.endpoint === "string" ? args.endpoint : null));
151 case "set_preferences":
152 return Response.json(await stub.setPreferences(args.preferences));
153 case "last_visit":
154 case "mark_visit": {
155 const workspace = visitWorkspace(args.workspace);
156 if (!workspace) return Response.json({ seen_at: null });
157 return Response.json(method === "last_visit" ? await stub.lastVisit(workspace) : await stub.markVisit(workspace, args.at));
158 }
159 case "watch_repo": {
160 const repoId = cleanRepoId(args.repo_id);
161 const repo = cleanRepoPath(args.repo);
162 if (!repoId || !repo) return Response.json({ ok: false, until: null });
163 return Response.json(await stub.watchRepo(userId, repoId, repo));
164 }
165 case "forget_conversation": {
166 // For chat, after the person cleared their direct message with @g1t (src/forget.ts).
167 const channelId = cleanChannelId(args.channel_id);
168 const workspace = visitWorkspace(args.workspace);
169 if (!channelId || !workspace) return Response.json({ ok: false });
170 return Response.json(await stub.forgetConversation(workspace, channelId));
171 }
172 case "test":
173 return Response.json(await stub.test(typeof args.username === "string" ? args.username : ""));
174 case "presence":
175 return Response.json(await stub.own({ user_id: userId, username: typeof args.username === "string" ? args.username : "" }));
176 case "set_presence":
177 return Response.json(
178 await stub.setPresence({ user_id: userId, username: typeof args.username === "string" ? args.username : "" }, args.change ?? {}),
179 );
180 default:
181 return new Response("Unknown method\n", { status: 404 });
182 }
183}
184
185/**
186 * `GET /live`, upgraded: the viewer comes in NOTIFY_VIEWER_HEADER, set by
187 * the site after checking the session; trusted only because this Worker
188 * is reachable through service bindings alone.
189 */
190async function live(request: Request, env: Env): Promise<Response> {
191 if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
192 return new Response("Expected a WebSocket upgrade\n", { status: 426 });
193 }
194 let viewer: Viewer = null;
195 try {
196 viewer = JSON.parse(request.headers.get(NOTIFY_VIEWER_HEADER) ?? "null") as Viewer;
197 } catch {
198 viewer = null;
199 }
200 if (!viewer?.id) return new Response("Sign in first\n", { status: 401 });
201 const headers = new Headers(request.headers);
202 headers.delete(NOTIFY_VIEWER_HEADER);
203 // Who the feed is for, so it can name them to the presence rooms.
204 headers.set(FEED_USER_ID_HEADER, viewer.id);
205 headers.set(FEED_USERNAME_HEADER, viewer.username);
206 return feed(env, viewer.id).fetch(new Request(request.url, { method: "GET", headers }));
207}
208
209export default {
210 async fetch(request: Request, env: Env): Promise<Response> {
211 const url = new URL(request.url);
212 if (request.method === "GET" && url.pathname === "/live") return live(request, env);
213 const match = url.pathname.match(/^\/rpc\/([a-z_]+)$/);
214 if (request.method !== "POST" || !match) return new Response("Not found\n", { status: 404 });
215 const args = (await request.json().catch(() => ({}))) as any;
216 return answer(env, match[1], args);
217 },
218} satisfies ExportedHandler<Env>;
219