Open History to see the last commit
1import {
2 WS_METHODS,
3 PullRequestRef,
4 PullRequestInvalidateInput,
5 type EnvironmentId,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as Cause from "effect/Cause";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11import * as SubscriptionRef from "effect/SubscriptionRef";
12
13import { EnvironmentRegistry, EnvironmentNotRegisteredError } from "../connection/registry.ts";
14import { EnvironmentSupervisor } from "../connection/supervisor.ts";
15import {
16 GitHubRoutingPermissions,
17 gitHubRoutingConnectionKey,
18} from "../connection/githubRoutingPermissions.ts";
19import type { ConnectionCatalogEntry } from "../connection/catalog.ts";
20import { ConnectionProfileStore } from "../connection/profileStore.ts";
21import {
22 request,
23 EnvironmentRpcUnavailableError,
24 type EnvironmentRpcInput,
25 type EnvironmentUnaryRpcTag,
26} from "../rpc/client.ts";
27
28const reads = new Set<string>([
29 WS_METHODS.pullRequestsSummary,
30 WS_METHODS.pullRequestsStack,
31 WS_METHODS.pullRequestsDetail,
32 WS_METHODS.pullRequestsPreview,
33 WS_METHODS.pullRequestsChecks,
34 WS_METHODS.pullRequestsActivity,
35 WS_METHODS.pullRequestsThreadComments,
36 WS_METHODS.pullRequestsDiffFileContents,
37 WS_METHODS.pullRequestsFilesViewed,
38 WS_METHODS.pullRequestsReviewerCandidates,
39 WS_METHODS.pullRequestsLabelCandidates,
40]);
41const writes = new Set<string>([
42 WS_METHODS.pullRequestsSetFilesViewed,
43 WS_METHODS.pullRequestsRunAction,
44 WS_METHODS.pullRequestsUpdate,
45 WS_METHODS.pullRequestsComment,
46 WS_METHODS.pullRequestsUpdateComment,
47 WS_METHODS.pullRequestsSubmitReview,
48 WS_METHODS.pullRequestsReplyToThread,
49 WS_METHODS.pullRequestsSetReaction,
50 WS_METHODS.pullRequestsSetThreadResolution,
51 WS_METHODS.pullRequestsRequestReviewers,
52 WS_METHODS.pullRequestsSetLabels,
53]);
54const isRef = Schema.is(PullRequestRef);
55const isInvalidation = Schema.is(PullRequestInvalidateInput);
56const readTimeout = (environmentId: EnvironmentId) =>
57 Effect.timeoutOrElse({
58 duration: "30 seconds",
59 orElse: () =>
60 Effect.fail(
61 new EnvironmentRpcUnavailableError({
62 environmentId,
63 message: "The environment did not respond to the PR request.",
64 }),
65 ),
66 });
67interface RoutedRead {
68 origin: EnvironmentId;
69 reference: PullRequestRef;
70 targets: Set<EnvironmentId>;
71}
72const routedReads = new WeakMap<EnvironmentRegistry["Service"], Map<string, RoutedRead>>();
73const isUnregistered = Schema.is(EnvironmentNotRegisteredError);
74const encodeKey = Schema.encodeSync(
75 Schema.fromJsonString(Schema.Array(Schema.NullOr(Schema.String))),
76);
77
78function isLocal(entry: ConnectionCatalogEntry): boolean {
79 const url =
80 entry.target._tag === "PrimaryConnectionTarget"
81 ? entry.target.httpBaseUrl
82 : Option.isSome(entry.profile) && entry.profile.value._tag === "BearerConnectionProfile"
83 ? entry.profile.value.httpBaseUrl
84 : undefined;
85 if (url === undefined) return false;
86 try {
87 return ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);
88 } catch {
89 return false;
90 }
91}
92
93/** A guard rejection is returned before the operation starts. Other write failures are ambiguous. */
94function rejectedBeforeDispatch(error: unknown): boolean {
95 return (
96 typeof error === "object" &&
97 error !== null &&
98 "_tag" in error &&
99 (error._tag === "EnvironmentRpcUnavailableError" ||
100 error._tag === "EnvironmentNotRegisteredError" ||
101 (error._tag === "PullRequestOperationError" &&
102 "operation" in error &&
103 error.operation === "routeIdentity"))
104 );
105}
106
107const routingAllowed = Effect.fn("PullRequestRouting.allowed")(function* (
108 registry: EnvironmentRegistry["Service"],
109 originId: EnvironmentId,
110 destinationId: EnvironmentId,
111 write: boolean,
112) {
113 const entries = yield* SubscriptionRef.get(registry.entries);
114 const origin = entries.get(originId);
115 const destination = entries.get(destinationId);
116 if (!origin?.enabled || !destination?.enabled) return false;
117 const permissions = yield* GitHubRoutingPermissions;
118 const source = yield* permissions.get(origin);
119 const target = yield* permissions.get(destination);
120 const allowed = write
121 ? source === "read-write" && target === "read-write"
122 : source !== "off" && target !== "off";
123 if (!allowed) return false;
124 for (const entry of [origin, destination]) {
125 if (entry.target._tag !== "SshConnectionTarget") continue;
126 const profiles = yield* Effect.serviceOption(ConnectionProfileStore);
127 if (Option.isNone(profiles)) return false;
128 const profile = yield* profiles.value
129 .get(entry.target.connectionId)
130 .pipe(Effect.orElseSucceed(() => Option.none()));
131 const key = gitHubRoutingConnectionKey(entry);
132 if (key === null || key !== gitHubRoutingConnectionKey({ ...entry, profile })) return false;
133 }
134 return true;
135});
136
137function matchesReference(reference: PullRequestRef, filter: PullRequestRef): boolean {
138 return (
139 reference.projectId === filter.projectId &&
140 reference.repository.toLowerCase() === filter.repository.toLowerCase() &&
141 reference.number === filter.number &&
142 (filter.host === undefined || reference.host?.toLowerCase() === filter.host.toLowerCase())
143 );
144}
145
146const invalidateTarget = Effect.fn("PullRequestRouting.invalidateTarget")(function* (
147 registry: EnvironmentRegistry["Service"],
148 origin: EnvironmentId,
149 target: EnvironmentId,
150 inputs: ReadonlyArray<PullRequestInvalidateInput>,
151) {
152 if (target !== origin && !(yield* routingAllowed(registry, origin, target, false))) return;
153 yield* Effect.forEach(
154 inputs,
155 (input) =>
156 registry.run(target, request(WS_METHODS.pullRequestsInvalidate, input)).pipe(
157 // GitHub already accepted the write. A stalled reader must not delay its confirmation.
158 Effect.timeoutOption("1 second"),
159 Effect.orElseSucceed(() => undefined),
160 ),
161 { concurrency: 3, discard: true },
162 );
163});
164
165/** Credentials stay on their environments. Only a verified host and account cross the wire. */
166export function createPullRequestRouter() {
167 const routedRequest = Effect.fn("PullRequestRouting.request")(function* <
168 T extends EnvironmentUnaryRpcTag,
169 >(tag: T, input: EnvironmentRpcInput<T>, sourceRead?: ReturnType<typeof request<T>>) {
170 const source = sourceRead ?? request(tag, input);
171 if (tag === WS_METHODS.pullRequestsInvalidate && isInvalidation(input)) {
172 const result = yield* request(tag, input);
173 const origin = yield* EnvironmentSupervisor;
174 const registry = yield* EnvironmentRegistry;
175 const used = routedReads.get(registry);
176 const targets = new Map<EnvironmentId, PullRequestRef>();
177 for (const entry of used?.values() ?? []) {
178 if (entry.origin !== origin.target.environmentId) continue;
179 const ref = input.reference;
180 if (ref !== undefined && !matchesReference(entry.reference, ref)) continue;
181 for (const target of entry.targets) targets.set(target, entry.reference);
182 if (input.reference !== undefined)
183 targets.set(origin.target.environmentId, entry.reference);
184 }
185 yield* Effect.forEach(
186 targets,
187 ([target, reference]) =>
188 invalidateTarget(registry, origin.target.environmentId, target, [
189 { ...input, ...(input.reference === undefined ? {} : { reference }) },
190 ]),
191 { concurrency: 4, discard: true },
192 );
193 return result;
194 }
195 if ((!reads.has(tag) && !writes.has(tag)) || !isRef(input)) {
196 return yield* request(tag, input);
197 }
198 const ref = input;
199 const origin = yield* EnvironmentSupervisor;
200 const registry = yield* EnvironmentRegistry;
201 const entries = yield* SubscriptionRef.get(registry.entries);
202 const sourceEntry = entries.get(origin.target.environmentId);
203 const used = routedReads.get(registry) ?? new Map<string, RoutedRead>();
204 routedReads.set(registry, used);
205 const refKey = encodeKey([
206 origin.target.environmentId,
207 ref.projectId,
208 ref.host?.toLowerCase() ?? null,
209 ref.repository.toLowerCase(),
210 String(ref.number),
211 ]);
212 const finish = (operation: ReturnType<typeof request<T>>) =>
213 operation.pipe(
214 Effect.tap(() => {
215 if (!writes.has(tag) || used.size === 0) return Effect.void;
216 const targets = new Map<EnvironmentId, PullRequestRef[]>([
217 [origin.target.environmentId, [ref]],
218 ]);
219 for (const entry of used.values()) {
220 if (
221 entry.origin !== origin.target.environmentId ||
222 !matchesReference(entry.reference, ref)
223 )
224 continue;
225 for (const target of [...entry.targets, origin.target.environmentId]) {
226 const refs = targets.get(target) ?? [];
227 if (!refs.some((existing) => existing.host === entry.reference.host))
228 refs.push(entry.reference);
229 targets.set(target, refs);
230 }
231 }
232 return Effect.forEach(
233 targets,
234 ([target, refs]) =>
235 invalidateTarget(registry, origin.target.environmentId, target, [
236 ...refs.map((reference) => ({
237 reference,
238 ...(tag === WS_METHODS.pullRequestsSetFilesViewed
239 ? { filesViewedOnly: true }
240 : {}),
241 })),
242 ...(tag === WS_METHODS.pullRequestsSetFilesViewed ? [] : [{}]),
243 ]),
244 { concurrency: 4, discard: true },
245 );
246 }),
247 );
248 const alternatives = [];
249 for (const [id, entry] of entries) {
250 if (id === origin.target.environmentId) continue;
251 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
252 continue;
253 const connected = yield* registry
254 .run(id, EnvironmentSupervisor.pipe(Effect.flatMap((s) => SubscriptionRef.get(s.session))))
255 .pipe(Effect.orElseSucceed(() => Option.none()));
256 if (Option.isNone(connected)) continue;
257 if (tag === WS_METHODS.pullRequestsChecks) {
258 const supported = yield* connected.value.initialConfig.pipe(
259 Effect.map((config) => config.environment.capabilities.pullRequestChecks === true),
260 Effect.timeout("2 seconds"),
261 Effect.catchCause((cause) =>
262 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(false),
263 ),
264 );
265 if (!supported) continue;
266 }
267 alternatives.push({ id, local: isLocal(entry) });
268 }
269 if (alternatives.length === 0) return yield* finish(source);
270
271 const identity = yield* request(WS_METHODS.pullRequestsRouting, ref).pipe(
272 Effect.timeout("2 seconds"),
273 Effect.catchCause((cause) =>
274 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
275 ),
276 );
277 // Old servers and unknown accounts retain the existing path.
278 if (identity === null || identity.provider !== "github") return yield* finish(source);
279
280 const routedInput = {
281 ...input,
282 host: identity.host,
283 expectedAccountId: identity.accountId,
284 };
285 const guardedSource = sourceRead ?? (yield* Effect.cached(request(tag, routedInput)));
286 const local = alternatives.filter((entry) => entry.local);
287 const remote = alternatives.filter((entry) => !entry.local);
288 const sourceLocal = sourceEntry !== undefined && isLocal(sourceEntry);
289 const candidates = [
290 ...(sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
291 ...local.map((entry) => entry.id),
292 ...(!sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
293 ...remote.map((entry) => entry.id),
294 ...(reads.has(tag) ? [origin.target.environmentId] : []),
295 ];
296 const run = (id: EnvironmentId): ReturnType<typeof request<T>> =>
297 (id === origin.target.environmentId
298 ? guardedSource
299 : registry.run(id, request(tag, routedInput))
300 ).pipe(
301 Effect.tap(() =>
302 Effect.sync(() => {
303 const entry = used.get(refKey) ?? {
304 origin: origin.target.environmentId,
305 reference: { ...ref, host: identity.host },
306 targets: new Set<EnvironmentId>(),
307 };
308 entry.targets.add(id);
309 if (used.size >= 256 && !used.has(refKey)) {
310 const oldest = used.keys().next().value;
311 if (oldest !== undefined) used.delete(oldest);
312 }
313 used.set(refKey, entry);
314 }),
315 ),
316 Effect.mapError((error) =>
317 isUnregistered(error)
318 ? new EnvironmentRpcUnavailableError({
319 environmentId: id,
320 message: "The environment was removed.",
321 })
322 : error,
323 ),
324 );
325 const visit = (index: number): ReturnType<typeof request<T>> => {
326 const id = candidates[index];
327 if (id === undefined) return guardedSource;
328 return Effect.gen(function* () {
329 if (id !== origin.target.environmentId) {
330 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
331 return yield* visit(index + 1);
332 // An older server would discard expectedAccountId. Verify it implements the guard first.
333 const alternate = yield* registry
334 .run(id, request(WS_METHODS.pullRequestsRoutingIdentity, { host: identity.host }))
335 .pipe(
336 Effect.timeout("2 seconds"),
337 Effect.catchCause((cause) =>
338 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
339 ),
340 );
341 if (
342 alternate === null ||
343 alternate.provider !== "github" ||
344 alternate.host.toLowerCase() !== identity.host.toLowerCase() ||
345 alternate.accountId !== identity.accountId
346 ) {
347 return yield* visit(index + 1);
348 }
349 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
350 return yield* visit(index + 1);
351 }
352 const operation = run(id);
353 return yield* (reads.has(tag) ? operation.pipe(readTimeout(id)) : operation).pipe(
354 Effect.catch((error) => {
355 if (
356 (reads.has(tag) || rejectedBeforeDispatch(error)) &&
357 index + 1 < candidates.length
358 ) {
359 return visit(index + 1);
360 }
361 return Effect.fail(error);
362 }),
363 Effect.map((result) =>
364 typeof result === "object" && result !== null && "projectId" in result
365 ? {
366 ...result,
367 projectId: ref.projectId,
368 ...(tag === WS_METHODS.pullRequestsDetail
369 ? { projectTitle: identity.projectTitle, workspaceRoot: identity.workspaceRoot }
370 : {}),
371 }
372 : result,
373 ),
374 );
375 });
376 };
377 return yield* finish(visit(0));
378 });
379
380 return Effect.fn("PullRequestRouting.readOrWrite")(function* <T extends EnvironmentUnaryRpcTag>(
381 tag: T,
382 input: EnvironmentRpcInput<T>,
383 ) {
384 if (!reads.has(tag) || !isRef(input)) return yield* routedRequest(tag, input);
385 const registry = yield* EnvironmentRegistry;
386 const entries = yield* SubscriptionRef.get(registry.entries);
387 if (entries.size < 2) return yield* request(tag, input);
388 const origin = yield* EnvironmentSupervisor;
389 let allowed = false;
390 for (const id of entries.keys()) {
391 if (
392 id !== origin.target.environmentId &&
393 (yield* routingAllowed(registry, origin.target.environmentId, id, false))
394 ) {
395 allowed = true;
396 break;
397 }
398 }
399 if (!allowed) return yield* request(tag, input);
400 const strictInput = { ...input, allowStale: false };
401 const source = yield* Effect.cached(
402 request(tag, strictInput).pipe(readTimeout(origin.target.environmentId)),
403 );
404 const sourceEntry = entries.get(origin.target.environmentId);
405 const routed = routedRequest(tag, strictInput, source);
406 return yield* (
407 sourceEntry !== undefined && isLocal(sourceEntry)
408 ? source.pipe(Effect.catch(() => routed))
409 : routed
410 ).pipe(
411 Effect.catch((error) =>
412 input.allowStale !== false &&
413 (tag === WS_METHODS.pullRequestsSummary || tag === WS_METHODS.pullRequestsDetail)
414 ? request(tag, input)
415 : Effect.fail(error),
416 ),
417 );
418 });
419}