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

pullRequestRouting.ts

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