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