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