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.

391 linesCodeBlameRaw
1/**
2 * Home's reads: each section's data from its own service, every call on
3 * its own so one that fails leaves only its section saying so. The shaping
4 * is in ./home.ts.
5 */
6import { env } from "cloudflare:workers";
7
8import {
9 type ActivityDigest,
10 type ChatActivity,
11 type Commit,
12 type Deployment,
13 type G1tEvent,
14 type InboxItem,
15 MAX_DIGEST_REPOS,
16 type ProjectDeploys,
17 type PullSessions,
18 type Repo,
19 type RepoPath,
20 type ShippedRepo,
21 type User,
22 type WorkflowRun,
23 notifyClient,
24 G1T_KEY,
25} from "@g1t/contracts";
26
27import {
28 type CodePull,
29 type CodeWork,
30 type DirectPush,
31 G1T_ACTOR,
32 type LandedChange,
33 type RepoRef,
34 type Span,
35 type Spend,
36 deployActorKey,
37 shippedAsks,
38 spanMonths,
39 spendIn,
40} from "./home";
41import { monthSpan } from "./usage";
42import { actions, billing, chat, deployments, events, identity, inbox, repos, work } from "./services.server";
43
44/** Pull requests read per project and list: `LIST_PAGE` in services/work. */
45const PULL_PAGE = 100;
46/** The most projects whose pull requests are read. */
47const MAX_PROJECTS = 50;
48/** The most projects whose builds are read for the span. */
49const MAX_DEPLOY_PROJECTS = 20;
50/** The most projects whose workflow runs are read for Running now: those pushed to most in the span. */
51const MAX_WORKFLOW_PROJECTS = 10;
52/** Runs read per project: enough to find the ones not finished. */
53const WORKFLOW_RUNS = 20;
54/** The most member keys named in one lookup. */
55const MAX_NAMES = 200;
56const DAY = 24 * 60 * 60 * 1000;
57
58const warn = (what: string) => (error: unknown) => {
59 console.warn(`home: ${what} failed`, error);
60 return null;
61};
62
63/**
64 * When the viewer was last on this workspace's Home, from notify, where it
65 * is kept with them (the same on every device). Null when there is no
66 * visit on record; undefined when notify did not answer.
67 */
68export async function loadLastVisit(viewer: User, slug: string): Promise<number | null | undefined> {
69 if (!env.NOTIFY) return undefined;
70 const visit = await notifyClient(env.NOTIFY).lastVisit(viewer, slug).catch(warn("last visit"));
71 if (!visit) return undefined;
72 return visit.seen_at ? Date.parse(visit.seen_at) : null;
73}
74
75/** Marks the viewer's visit at `at`, the time the page they looked at loaded. */
76export async function markVisit(viewer: User, slug: string, at: number): Promise<boolean> {
77 if (!env.NOTIFY) return false;
78 const marked = await notifyClient(env.NOTIFY).markVisit(viewer, slug, new Date(at).toISOString()).catch(warn("mark visit"));
79 return marked != null;
80}
81
82/**
83 * The workspace's own repositories the viewer may read (no pull request
84 * working copies), as every Code section reads them. Null when repos did
85 * not answer.
86 */
87export async function loadRepos(viewer: User, slug: string): Promise<Repo[] | null> {
88 const list = await repos.list(viewer, { namespace: slug }).catch(warn("repos"));
89 return list ? list.filter((repo) => !repo.forkOf && repo.namespace.toLowerCase() === slug) : null;
90}
91
92/** The repositories by id, as the digest's lines and links need them. */
93export function repoRefs(list: Repo[] | null): Record<string, RepoRef> {
94 const refs: Record<string, RepoRef> = {};
95 for (const repo of list ?? []) refs[repo.id] = { namespace: repo.namespace, name: repo.name, defaultBranch: repo.defaultBranch };
96 return refs;
97}
98
99/**
100 * The workspace's projects' pull requests, open and recently merged or
101 * closed, any author's. `complete` when every list reaches back to
102 * `reach`. Null when Code did not answer.
103 */
104export async function loadCodeWork(viewer: User, slug: string, reach: number, owned: Repo[] | null): Promise<CodeWork | null> {
105 if (!owned) return null;
106 const chosen = owned.slice(0, MAX_PROJECTS);
107 const byId = new Map<string, Repo>(chosen.map((repo) => [repo.id, repo]));
108 const batch = chosen.length > 0 ? await work.pullsForRepos([...byId.keys()], viewer, PULL_PAGE).catch(warn("pull requests")) : [];
109 if (!batch) return null;
110 const pulls: CodePull[] = [];
111 let complete = owned.length <= MAX_PROJECTS;
112 for (const entry of batch) {
113 const repo = byId.get(entry.repoId);
114 if (!repo) continue;
115 const path = { namespace: repo.namespace, name: repo.name };
116 for (const pull of [...entry.open, ...entry.closed]) {
117 pulls.push({
118 repo: path,
119 repoId: repo.id,
120 mergeCommit: pull.mergeCommit ?? null,
121 number: pull.number,
122 title: pull.title,
123 status: pull.status,
124 mergedAt: pull.mergedAt,
125 mergedBy: pull.mergedBy,
126 createdAt: pull.createdAt,
127 updatedAt: pull.updatedAt,
128 author: { username: pull.author.username, kind: pull.author.kind },
129 });
130 }
131 // A full page that does not reach back far enough may leave some out.
132 for (const list of [entry.open, entry.closed]) {
133 if (list.length >= PULL_PAGE) {
134 const oldest = Math.min(...list.map((pull) => Date.parse(pull.mergedAt ?? pull.updatedAt)));
135 if (oldest > reach) complete = false;
136 }
137 }
138 }
139 return { pulls, complete };
140}
141
142/**
143 * What happened in the span, counted by who did it: the events service's
144 * digest of the workspace's repositories (the first MAX_DIGEST_REPOS of
145 * them; none without Code access) and of its artifacts. Null when events
146 * did not answer.
147 */
148export async function loadActivity(slug: string, span: Pick<Span, "from" | "now">, owned: Repo[] | null): Promise<ActivityDigest | null> {
149 const digest = await events
150 .activityDigest({
151 repo_ids: (owned ?? []).slice(0, MAX_DIGEST_REPOS).map((repo) => repo.id),
152 workspace: slug,
153 from: new Date(span.from).toISOString(),
154 until: new Date(span.now + 1).toISOString(),
155 })
156 .catch(warn("activity digest"));
157 if (!digest) return null;
158 // More repositories than the digest reads: it says so.
159 return owned && owned.length > MAX_DIGEST_REPOS ? { ...digest, complete: false } : digest;
160}
161
162/** What was said in the span where the viewer can read, counted. Null when chat did not answer. */
163export async function loadChatActivity(viewer: User, slug: string, span: Pick<Span, "from" | "now">): Promise<ChatActivity | null> {
164 const activity = await chat
165 .activity(slug, viewer, { from: new Date(span.from).toISOString(), until: new Date(span.now + 1).toISOString() })
166 .catch(warn("chat activity"));
167 return activity?.ok ? activity.value : null;
168}
169
170/** Every member key the digest and chat name. */
171export function actorKeys(activity: ActivityDigest | null, chatActivity: ChatActivity | null, deploys?: { projects: { deployments: { createdBy: string }[] }[] } | null): string[] {
172 const keys = new Set<string>();
173 for (const project of deploys?.projects ?? []) for (const deploy of project.deployments) keys.add(deployActorKey(deploy.createdBy) ?? "");
174 for (const repo of activity?.repos ?? []) {
175 for (const by of [...repo.pushes.by, ...repo.pushes.default_branch.by]) keys.add(by.actor);
176 for (const list of [repo.pulls.opened, repo.pulls.merged, repo.pulls.closed, repo.issues.opened, repo.issues.closed, repo.reviews, repo.comments, repo.deployments.succeeded, repo.deployments.failed]) {
177 for (const entry of list) keys.add(entry.actor);
178 }
179 for (const release of repo.releases) keys.add(release.actor);
180 for (const pkg of repo.packages) keys.add(pkg.actor);
181 }
182 for (const entry of activity?.folios?.created ?? []) keys.add(entry.actor);
183 for (const folio of activity?.folios?.edited ?? []) for (const author of folio.authors) keys.add(author);
184 for (const author of chatActivity?.authors ?? []) keys.add(author.key);
185 keys.delete("");
186 return [...keys];
187}
188
189/**
190 * The names behind member keys: people's usernames from identity (one
191 * lookup for them all), g1t as itself. A key identity does not know, and
192 * an agent of older rows, is left out, and shows as "someone".
193 */
194export async function loadNames(keys: string[]): Promise<Record<string, string>> {
195 const names: Record<string, string> = {};
196 const userIds: string[] = [];
197 for (const key of keys.slice(0, MAX_NAMES)) {
198 if (key === G1T_ACTOR || key === "user:g1t" || key === G1T_KEY || key.startsWith("user:wsp_")) names[key] = "g1t";
199 else if (key.startsWith("agent:") || key.startsWith("user:agt_")) continue;
200 else if (key.startsWith("user:")) userIds.push(key.slice("user:".length));
201 }
202 if (userIds.length > 0) {
203 const found = await identity.usernames(userIds).catch(warn("usernames"));
204 for (const [id, username] of Object.entries(found ?? {})) names[`user:${id}`] = username;
205 }
206 return names;
207}
208
209/**
210 * The newest workflow runs of the projects pushed to most in the span (at
211 * most MAX_WORKFLOW_PROJECTS), for the ones still going. A project whose
212 * runs could not be read is left out; `complete` says whether every one was.
213 */
214export async function loadWorkflowRuns(
215 viewer: User,
216 activity: ActivityDigest | null,
217 owned: Repo[] | null,
218): Promise<{ projects: { repo: RepoPath; runs: WorkflowRun[] }[]; complete: boolean }> {
219 const byId = new Map((owned ?? []).map((repo) => [repo.id, repo]));
220 const active = [...(activity?.repos ?? [])]
221 .filter((repo) => repo.pushes.count > 0 && byId.has(repo.repo_id))
222 .sort((a, b) => b.pushes.count - a.pushes.count || a.repo_id.localeCompare(b.repo_id))
223 .slice(0, MAX_WORKFLOW_PROJECTS);
224 const lists = await Promise.all(
225 active.map((digest) => {
226 const repo = byId.get(digest.repo_id)!;
227 const path = { namespace: repo.namespace, name: repo.name };
228 return actions
229 .runs(path, viewer, { limit: WORKFLOW_RUNS })
230 .then((result) => (result.ok ? { repo: path, runs: result.value } : null))
231 .catch(warn(`workflow runs of ${repo.name}`));
232 }),
233 );
234 const projects = lists.filter((entry) => entry != null);
235 return { projects, complete: projects.length === active.length };
236}
237
238/**
239 * Every project's builds at a glance, and the builds of the projects that
240 * deploy, for the span: the projects whose newest build is older than the
241 * span are not read again.
242 */
243export async function loadDeploys(
244 viewer: User,
245 slug: string,
246 from: number,
247): Promise<{ overview: ProjectDeploys[]; projects: { slug: string; deployments: Deployment[] }[]; complete: boolean } | null> {
248 const overview = await deployments.overview(slug, viewer).catch(warn("deploys overview"));
249 if (!overview?.ok) return null;
250 const recent = overview.value.filter((project) => project.latest && Date.parse(project.latest.finishedAt ?? project.latest.createdAt) >= from);
251 const read = recent.slice(0, MAX_DEPLOY_PROJECTS);
252 const lists = await Promise.all(
253 read.map((project) =>
254 deployments
255 .list({ workspace: slug, slug: project.slug }, viewer)
256 .then((result) => (result.ok ? { slug: project.slug, deployments: result.value.deployments } : null))
257 .catch(warn(`deploys of ${project.slug}`)),
258 ),
259 );
260 const projects = lists.filter((entry) => entry != null);
261 return { overview: overview.value, projects, complete: projects.length === recent.length };
262}
263
264/**
265 * The span's spend from the statements of the months it touches, and the
266 * month so far from the usage report Usage reads (`usage.ts` `monthSpan`,
267 * at price), so Home's figure is Usage's. Null
268 * when billing did not answer; the month alone null when only it did not.
269 */
270export async function loadSpend(viewer: User, slug: string, span: Pick<Span, "from" | "now">): Promise<Spend | null> {
271 const months = spanMonths(span);
272 const [statements, month] = await Promise.all([
273 Promise.all(months.map((month) => billing.statement(slug, viewer, month, "day").catch(warn(`statement ${month}`)))),
274 billing
275 .usageReport(slug, viewer, monthSpan(new Date(span.now)))
276 .then((result) => (result.ok ? result.value.totals.priceMicros : null))
277 .catch(warn("month usage")),
278 ]);
279 if (statements.some((statement) => !statement?.ok)) return null;
280 return spendIn(
281 statements.map((statement) => (statement as Extract<typeof statement, { ok: true }>).value),
282 span,
283 month,
284 );
285}
286
287/** The most projects whose pushes to the default branch are listed one by one, pushes read per project, and commits read back. */
288const MAX_PUSH_PROJECTS = 10;
289const PUSHES_READ = 100;
290const PUSH_HISTORY = 200;
291
292/**
293 * Each person's push to a default branch in the span, for the projects
294 * the digest says were pushed to (those pushed to most, at most
295 * MAX_PUSH_PROJECTS), with each project's default branch read back from
296 * its newest push to place each push's commits. `by` is the pusher's
297 * member key, named by the caller. Null when events did not answer.
298 */
299export async function loadDirectPushes(
300 viewer: User,
301 activity: ActivityDigest | null,
302 owned: Repo[] | null,
303 span: Pick<Span, "from" | "now">,
304): Promise<{ pushes: (Omit<DirectPush, "by"> & { actorKey: string })[]; history: Record<string, Commit[]>; complete: boolean } | null> {
305 if (!activity || !owned) return null;
306 const byId = new Map(owned.map((repo) => [repo.id, repo]));
307 const pushedTo = activity.repos
308 .filter((digest) => digest.pushes.default_branch.count > 0 && byId.has(digest.repo_id))
309 .sort((a, b) => b.pushes.default_branch.count - a.pushes.default_branch.count || a.repo_id.localeCompare(b.repo_id));
310 const read = pushedTo.slice(0, MAX_PUSH_PROJECTS);
311 const lists = await Promise.all(
312 read.map(async (digest) => {
313 const repo = byId.get(digest.repo_id)!;
314 const log = await events.list({ repoId: repo.id, types: ["git.push"], limit: PUSHES_READ }).catch(warn(`pushes of ${repo.name}`));
315 if (!log) return null;
316 const pushes = log.filter(
317 (event): event is G1tEvent<"git.push"> =>
318 event.type === "git.push" && (event as G1tEvent<"git.push">).data.defaultBranch && Date.parse(event.time) >= span.from && Date.parse(event.time) <= span.now,
319 );
320 if (pushes.length === 0) return { repo, pushes, history: [] as Commit[] };
321 const path = { namespace: repo.namespace, name: repo.name };
322 const history = await repos.log(path, viewer, pushes[0]!.data.after, PUSH_HISTORY).catch(warn(`history of ${repo.name}`));
323 return { repo, pushes, history: history?.ok ? history.value : [] };
324 }),
325 );
326 const pushes: (Omit<DirectPush, "by"> & { actorKey: string })[] = [];
327 const history: Record<string, Commit[]> = {};
328 for (const entry of lists) {
329 if (!entry) continue;
330 history[entry.repo.id] = entry.history;
331 const ref: RepoRef = { namespace: entry.repo.namespace, name: entry.repo.name, defaultBranch: entry.repo.defaultBranch };
332 for (const event of entry.pushes) {
333 pushes.push({
334 repoId: entry.repo.id,
335 repo: ref,
336 push: { id: event.id, time: event.time, actor: event.actor ?? null, data: event.data },
337 actorKey: event.actor ? deployActorKey(event.actor) ?? "" : "",
338 });
339 }
340 }
341 return { pushes, history, complete: lists.every((entry) => entry != null) && pushedTo.length <= MAX_PUSH_PROJECTS };
342}
343
344/**
345 * Whether each merge and push that landed went live, from deployments'
346 * record of what each production deployment shipped. Null when
347 * deployments did not answer.
348 */
349export async function loadShipped(viewer: User, slug: string, rows: LandedChange[]): Promise<ShippedRepo[] | null> {
350 const asks = shippedAsks(rows).slice(0, 20);
351 if (asks.length === 0) return [];
352 const answer = await deployments.shipped(slug, viewer, asks).catch(warn("shipped"));
353 return answer?.ok ? answer.value : null;
354}
355
356/** The harness sessions tied to each merged pull request, per project; null when work did not answer for any. */
357export async function loadPullSessions(viewer: User, pulls: CodePull[]): Promise<{ repo: RepoPath; pulls: PullSessions[] }[] | null> {
358 const byRepo = new Map<string, { repo: RepoPath; numbers: number[] }>();
359 for (const pull of pulls) {
360 if (pull.status !== "merged") continue;
361 const key = `${pull.repo.namespace}/${pull.repo.name}`.toLowerCase();
362 const entry = byRepo.get(key) ?? { repo: pull.repo, numbers: [] };
363 entry.numbers.push(pull.number);
364 byRepo.set(key, entry);
365 }
366 if (byRepo.size === 0) return [];
367 const lists = await Promise.all(
368 [...byRepo.values()].slice(0, MAX_PUSH_PROJECTS).map(({ repo, numbers }) =>
369 work
370 .pullSessions(repo, viewer, numbers.slice(0, 100))
371 .then((result) => (result.ok ? { repo, pulls: result.value } : null))
372 .catch(warn(`sessions of ${repo.name}`)),
373 ),
374 );
375 const found = lists.filter((entry) => entry != null);
376 return found.length === 0 && lists.length > 0 ? null : found;
377}
378
379/** Notifications read for what settled by itself in the span. */
380const SETTLED_READ = 100;
381
382/** The viewer's notifications done since the span began, newest activity first; null when the inbox did not answer. */
383export async function loadSettled(viewer: User, span: Pick<Span, "from">): Promise<InboxItem[] | null> {
384 const page = await inbox.list(viewer, { view: "done", limit: SETTLED_READ }).catch(warn("settled notifications"));
385 return page ? page.items.filter((item) => item.doneAt != null && Date.parse(item.doneAt) >= span.from) : null;
386}
387
388/** How far back Code is read: 7 days before the span, for the comparison. */
389export function reachFor(span: Pick<Span, "from">): number {
390 return span.from - 7 * DAY;
391}