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