Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pullRequestRouting.ts

507 lines19.6 KB

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]);
47// Review guides are not routed: each server keeps its own, so another server answering would
48// report none, or start a run nobody on the pull request's own server can see.
49const writes = new Set<string>([
50 WS_METHODS.pullRequestsSetFilesViewed,
51 WS_METHODS.pullRequestsRunAction,
52 WS_METHODS.pullRequestsUpdate,
53 WS_METHODS.pullRequestsComment,
54 WS_METHODS.pullRequestsUpdateComment,
55 WS_METHODS.pullRequestsSubmitReview,
56 WS_METHODS.pullRequestsReplyToThread,
57 WS_METHODS.pullRequestsSetReaction,
58 WS_METHODS.pullRequestsSetThreadResolution,
59 WS_METHODS.pullRequestsRequestReviewers,
60 WS_METHODS.pullRequestsSetLabels,
61]);
62const isRef = Schema.is(PullRequestRef);
63const hasState = Schema.is(Schema.Struct({ state: PullRequestState }));
64const isInvalidation = Schema.is(PullRequestInvalidateInput);
65const readTimeout = (environmentId: EnvironmentId) =>
66 Effect.timeoutOrElse({
67 duration: "30 seconds",
68 orElse: () =>
69 Effect.fail(
70 new EnvironmentRpcUnavailableError({
71 environmentId,
72 message: "The environment did not respond to the PR request.",
73 }),
74 ),
75 });
76interface RoutedRead {
77 origin: EnvironmentId;
78 reference: PullRequestRef;
79 targets: Set<EnvironmentId>;
81const routedReads = new WeakMap<
82 EnvironmentRegistry.EnvironmentRegistry["Service"],
83 Map<string, RoutedRead>
84>();
85const isUnregistered = Schema.is(EnvironmentRegistry.EnvironmentNotRegisteredError);
86const encodeKey = Schema.encodeSync(
87 Schema.fromJsonString(Schema.Array(Schema.NullOr(Schema.String))),
88);
89type PendingMetadata<A> = WeakMap<RpcSession, Map<string, Deferred.Deferred<Exit.Exit<A>>>>;
90const pendingRouting: PendingMetadata<PullRequestRoutingResult | null> = new WeakMap();
91const pendingIdentities: PendingMetadata<PullRequestRoutingIdentityResult | null> = new WeakMap();
92​
93function shareMetadataRead<A, R>(
94 pending: PendingMetadata<A>,
95 key: string,
96 probe: Effect.Effect<A, never, R>,
97): Effect.Effect<A, never, R | EnvironmentSupervisor.EnvironmentSupervisor> {
98 return Effect.uninterruptibleMask((restore) =>
99 Effect.gen(function* () {
100 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
101 const session = yield* SubscriptionRef.get(supervisor.session);
102 if (Option.isNone(session)) return yield* restore(probe);
103 const entries =
104 pending.get(session.value) ?? new Map<string, Deferred.Deferred<Exit.Exit<A>>>();
105 pending.set(session.value, entries);
106 const existing = entries.get(key);
107 if (existing !== undefined) {
108 const result = yield* restore(Deferred.await(existing));
109 // A cancelled first reader must not cancel the other readers waiting on its probe.
110 return yield* restore(
111 Exit.hasInterrupts(result) ? shareMetadataRead(pending, key, probe) : result,
112 );
113 }
114 const result = Deferred.makeUnsafe<Exit.Exit<A>>();
115 entries.set(key, result);
116 return yield* restore(probe).pipe(
117 Effect.onExit((exit) =>
118 Effect.sync(() => entries.delete(key)).pipe(
119 Effect.andThen(Deferred.succeed(result, exit)),
120 ),
121 ),
122 );
123 }),
124 );
126​
127function isLocal(entry: ConnectionCatalogEntry): boolean {
128 const url =
129 entry.target._tag === "PrimaryConnectionTarget"
130 ? entry.target.httpBaseUrl
131 : Option.isSome(entry.profile) && entry.profile.value._tag === "BearerConnectionProfile"
132 ? entry.profile.value.httpBaseUrl
133 : undefined;
134 if (url === undefined) return false;
135 try {
136 return ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);
137 } catch {
138 return false;
139 }
141​
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 );
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 );
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.
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 if (identity === null || identity.provider !== "github") return yield* finish(source);
353​
354 const routedInput = {
355 ...input,
356 host: identity.host,
357 expectedAccountId: identity.accountId,
358 };
359 const guardedSource = sourceRead ?? (yield* Effect.cached(request(tag, routedInput)));
360 const local = alternatives.filter((entry) => entry.local);
361 const remote = alternatives.filter((entry) => !entry.local);
362 const sourceLocal = sourceEntry !== undefined && isLocal(sourceEntry);
363 const candidates = [
364 ...(sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
365 ...local.map((entry) => entry.id),
366 ...(!sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
367 ...remote.map((entry) => entry.id),
368 ...(reads.has(tag) ? [origin.target.environmentId] : []),
369 ];
370 const run = (id: EnvironmentId): ReturnType<typeof request<T>> =>
371 (id === origin.target.environmentId
372 ? guardedSource
373 : registry.run(id, request(tag, routedInput))
374 ).pipe(
375 Effect.tap((result) =>
376 id !== origin.target.environmentId && hasState(result)
377 ? reportState(ref, result.state)
378 : Effect.void,
379 ),
380 Effect.tap(() =>
381 Effect.sync(() => {
382 const entry = used.get(refKey) ?? {
383 origin: origin.target.environmentId,
384 reference: { ...ref, host: identity.host },
385 targets: new Set<EnvironmentId>(),
386 };
387 entry.targets.add(id);
388 if (used.size >= 256 && !used.has(refKey)) {
389 const oldest = used.keys().next().value;
390 if (oldest !== undefined) used.delete(oldest);
391 }
392 used.set(refKey, entry);
393 }),
394 ),
395 Effect.mapError((error) =>
396 isUnregistered(error)
397 ? new EnvironmentRpcUnavailableError({
398 environmentId: id,
399 message: "The environment was removed.",
400 })
401 : error,
402 ),
403 );
404 const visit = (index: number): ReturnType<typeof request<T>> => {
405 const id = candidates[index];
406 if (id === undefined) return guardedSource;
407 return Effect.gen(function* () {
408 if (id !== origin.target.environmentId) {
409 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
410 return yield* visit(index + 1);
411 // An older server would discard expectedAccountId. Verify it implements the guard first.
412 const alternateProbe = request(WS_METHODS.pullRequestsRoutingIdentity, {
413 host: identity.host,
414 }).pipe(
415 Effect.timeout("2 seconds"),
416 Effect.catchCause((cause) =>
417 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
418 ),
419 );
420 const alternate = yield* registry
421 .run(
422 id,
423 reads.has(tag)
424 ? shareMetadataRead(pendingIdentities, identity.host.toLowerCase(), alternateProbe)
425 : alternateProbe,
426 )
427 .pipe(
428 Effect.timeout("2 seconds"),
429 Effect.catchCause((cause) =>
430 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
431 ),
432 );
433 if (
434 alternate === null ||
435 alternate.provider !== "github" ||
436 alternate.host.toLowerCase() !== identity.host.toLowerCase() ||
437 alternate.accountId !== identity.accountId
438 ) {
439 return yield* visit(index + 1);
440 }
441 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
442 return yield* visit(index + 1);
443 }
444 const operation = run(id);
445 return yield* (reads.has(tag) ? operation.pipe(readTimeout(id)) : operation).pipe(
446 Effect.catchIf(
447 (error) =>
448 (reads.has(tag) || rejectedBeforeDispatch(error)) && index + 1 < candidates.length,
449 () => visit(index + 1),
450 ),
451 Effect.map((result) =>
452 typeof result === "object" && result !== null && "projectId" in result
453 ? {
454 ...result,
455 projectId: ref.projectId,
456 ...(tag === WS_METHODS.pullRequestsDetail
457 ? { projectTitle: identity.projectTitle, workspaceRoot: identity.workspaceRoot }
458 : {}),
459 }
460 : result,
461 ),
462 );
463 });
464 };
465 return yield* finish(visit(0));
466 });
467​
468 return Effect.fn("PullRequestRouting.readOrWrite")(function* <T extends EnvironmentUnaryRpcTag>(
469 tag: T,
470 input: EnvironmentRpcInput<T>,
471 ) {
472 if (!reads.has(tag) || !isRef(input)) return yield* routedRequest(tag, input);
473 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
474 const entries = yield* SubscriptionRef.get(registry.entries);
475 if (entries.size < 2) return yield* request(tag, input);
476 const origin = yield* EnvironmentSupervisor.EnvironmentSupervisor;
477 let allowed = false;
478 for (const id of entries.keys()) {
479 if (
480 id !== origin.target.environmentId &&
481 (yield* routingAllowed(registry, origin.target.environmentId, id, false))
482 ) {
483 allowed = true;
484 break;
485 }
486 }
487 if (!allowed) return yield* request(tag, input);
488 const strictInput = { ...input, allowStale: false };
489 const source = yield* Effect.cached(
490 request(tag, strictInput).pipe(readTimeout(origin.target.environmentId)),
491 );
492 const sourceEntry = entries.get(origin.target.environmentId);
493 const routed = routedRequest(tag, strictInput, source);
494 return yield* (
495 sourceEntry !== undefined && isLocal(sourceEntry)
496 ? source.pipe(Effect.catch(() => routed))
497 : routed
498 ).pipe(
499 Effect.catch((error) =>
500 input.allowStale !== false &&
501 (tag === WS_METHODS.pullRequestsSummary || tag === WS_METHODS.pullRequestsDetail)
502 ? request(tag, input)
503 : Effect.fail(error),
504 ),
505 );
506 });