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
220 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 { settledThreads } from "./prefs.ts";
53import { byRepo, cleanRepoId, cleanRepoPath } from "./watch.ts";
54
55export { Feed } from "./feed.ts";
56export { Room } from "./room.ts";
57export { Topic } from "./topic.ts";
58
59type Env = FeedEnv & {
60 IDENTITY: ServiceBinding;
61 FEEDS: DurableObjectNamespace<Feed>;
62};
63
64function feed(env: Env, userId: string) {
65 return env.FEEDS.get(env.FEEDS.idFromName(userId));
66}
67
68/** A user id from the arguments, or one looked up by username. */
69async function userIdOf(env: Env, given: { user_id?: unknown; username?: unknown; target?: unknown }): Promise<string | null> {
70 // Who it's for, at the top level or under `target`.
71 const target = given.target && typeof given.target === "object" ? (given.target as { user_id?: unknown; username?: unknown }) : null;
72 const args = { user_id: given.user_id ?? target?.user_id, username: given.username ?? target?.username };
73 if (typeof args.user_id === "string" && args.user_id) return args.user_id;
74 if (typeof args.username !== "string" || !args.username) return null;
75 const user = await identityClient(env.IDENTITY)
76 .userByUsername(args.username)
77 .catch(() => null);
78 return user?.id ?? null;
79}
80
81/** The most deliveries in one call; chat sends one per person in the conversation. */
82const MAX_DELIVERIES = 1000;
83
84async function answer(env: Env, method: string, args: any): Promise<Response> {
85 if (method === "purge_personal_data") {
86 if (typeof args?.id !== "string" || !args.id) return Response.json({ ok: false }, { status: 400 });
87 if (args.kind === "user") return Response.json(await feed(env, args.id).erase(args.id));
88 if (args.kind !== "workspace" || typeof args.slug !== "string" || !args.slug) return Response.json({ ok: false }, { status: 400 });
89 // Every slug it went by, and everyone identity knew as a member when it
90 // was purged, besides those its presence rooms know: their feeds keep
91 // notifications, counts and visits under the slug.
92 const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((v): v is string => typeof v === "string" && v.length > 0) : []);
93 const slugs = [...new Set([args.slug, ...strings(args.old_slugs)].map((slug) => slug.toLowerCase()))];
94 const members = strings(args.members);
95 for (const slug of slugs) {
96 const room = env.ROOMS?.get(env.ROOMS.idFromName(slug));
97 const people = room ? await room.eraseMembers() : [];
98 const everyone = [...new Set([...people, ...members])];
99 for (let i = 0; i < everyone.length; i += 20) {
100 await Promise.all(everyone.slice(i, i + 20).map((userId) => feed(env, userId).eraseWorkspace(slug)));
101 }
102 // Only once their feeds are cleared, so a failure leaves them listed for the retry.
103 if (room) for (const userId of people) await room.dropPerson(userId);
104 }
105 return Response.json({ ok: true });
106 }
107 if (method === "workspace_presence") {
108 // For services: how a workspace's people show now, as its room keeps them.
109 const slug = typeof args?.workspace === "string" ? args.workspace.trim().toLowerCase() : "";
110 if (!slug || !env.ROOMS) return Response.json([]);
111 const everyone = await env.ROOMS.get(env.ROOMS.idFromName(slug)).people();
112 return Response.json(onlyPeople(everyone, Array.isArray(args.user_ids) ? args.user_ids : null));
113 }
114 if (method === "repo_changed") {
115 // For services: each repository's changes to its topic, which tells its watchers.
116 const topics = env.TOPICS;
117 if (!topics) return Response.json({ ok: true });
118 const grouped = byRepo(args?.changes);
119 const results = await Promise.allSettled([...grouped].map(([id, changes]) => topics.get(topics.idFromName(id)).changed(id, changes)));
120 for (const result of results) if (result.status === "rejected") console.error("notify: a repository's change was not told", result.reason);
121 return Response.json({ ok: true });
122 }
123 if (method === "deliver") {
124 const items = (Array.isArray(args?.items) ? args.items : []).slice(0, MAX_DELIVERIES) as FeedDelivery[];
125 const byUser = new Map<string, FeedDelivery[]>();
126 for (const item of items) {
127 if (typeof item?.user_id !== "string" || !item.user_id) continue;
128 byUser.set(item.user_id, [...(byUser.get(item.user_id) ?? []), item]);
129 }
130 const results = await Promise.allSettled([...byUser].map(([id, mine]) => feed(env, id).deliver(mine)));
131 for (const result of results) if (result.status === "rejected") console.error("notify: a delivery failed", result.reason);
132 return Response.json({ ok: true });
133 }
134 const userId = await userIdOf(env, args ?? {});
135 if (!userId) return Response.json({ ok: false });
136 const stub = feed(env, userId);
137 switch (method) {
138 case "notify":
139 return Response.json(await stub.notify(args.notification));
140 case "set_inbox":
141 return Response.json(await stub.setInbox(Number(args.unread), settledThreads(args.settled)));
142 case "subscribe":
143 return Response.json(await stub.subscribe(args.subscription, typeof args.user_agent === "string" ? args.user_agent : null));
144 case "unsubscribe":
145 return Response.json(await stub.unsubscribe(String(args.endpoint ?? "")));
146 case "register_device":
147 return Response.json(await stub.registerDevice(args.device));
148 case "unregister_device":
149 return Response.json(await stub.unregisterDevice(String(args.token ?? "")));
150 case "status":
151 return Response.json(await stub.status(typeof args.endpoint === "string" ? args.endpoint : null));
152 case "set_preferences":
153 return Response.json(await stub.setPreferences(args.preferences));
154 case "last_visit":
155 case "mark_visit": {
156 const workspace = visitWorkspace(args.workspace);
157 if (!workspace) return Response.json({ seen_at: null });
158 return Response.json(method === "last_visit" ? await stub.lastVisit(workspace) : await stub.markVisit(workspace, args.at));
159 }
160 case "watch_repo": {
161 const repoId = cleanRepoId(args.repo_id);
162 const repo = cleanRepoPath(args.repo);
163 if (!repoId || !repo) return Response.json({ ok: false, until: null });
164 return Response.json(await stub.watchRepo(userId, repoId, repo));
165 }
166 case "forget_conversation": {
167 // For chat, after the person cleared their direct message with @g1t (src/forget.ts).
168 const channelId = cleanChannelId(args.channel_id);
169 const workspace = visitWorkspace(args.workspace);
170 if (!channelId || !workspace) return Response.json({ ok: false });
171 return Response.json(await stub.forgetConversation(workspace, channelId));
172 }
173 case "test":
174 return Response.json(await stub.test(typeof args.username === "string" ? args.username : ""));
175 case "presence":
176 return Response.json(await stub.own({ user_id: userId, username: typeof args.username === "string" ? args.username : "" }));
177 case "set_presence":
178 return Response.json(
179 await stub.setPresence({ user_id: userId, username: typeof args.username === "string" ? args.username : "" }, args.change ?? {}),
180 );
181 default:
182 return new Response("Unknown method\n", { status: 404 });
183 }
184}
185
186/**
187 * `GET /live`, upgraded: the viewer comes in NOTIFY_VIEWER_HEADER, set by
188 * the site after checking the session; trusted only because this Worker
189 * is reachable through service bindings alone.
190 */
191async function live(request: Request, env: Env): Promise<Response> {
192 if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
193 return new Response("Expected a WebSocket upgrade\n", { status: 426 });
194 }
195 let viewer: Viewer = null;
196 try {
197 viewer = JSON.parse(request.headers.get(NOTIFY_VIEWER_HEADER) ?? "null") as Viewer;
198 } catch {
199 viewer = null;
200 }
201 if (!viewer?.id) return new Response("Sign in first\n", { status: 401 });
202 const headers = new Headers(request.headers);
203 headers.delete(NOTIFY_VIEWER_HEADER);
204 // Who the feed is for, so it can name them to the presence rooms.
205 headers.set(FEED_USER_ID_HEADER, viewer.id);
206 headers.set(FEED_USERNAME_HEADER, viewer.username);
207 return feed(env, viewer.id).fetch(new Request(request.url, { method: "GET", headers }));
208}
209
210export default {
211 async fetch(request: Request, env: Env): Promise<Response> {
212 const url = new URL(request.url);
213 if (request.method === "GET" && url.pathname === "/live") return live(request, env);
214 const match = url.pathname.match(/^\/rpc\/([a-z_]+)$/);
215 if (request.method !== "POST" || !match) return new Response("Not found\n", { status: 404 });
216 const args = (await request.json().catch(() => ({}))) as any;
217 return answer(env, match[1], args);
218 },
219} satisfies ExportedHandler<Env>;
220