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

pullRequestRouting.ts

510 lines19.7 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 (
165 !origin?.enabled ||
166 !destination?.enabled ||
167 origin.unsupportedReason !== undefined ||
168 destination.unsupportedReason !== undefined
169 )
170 return false;
171 const permissions = yield* GitHubRoutingPermissions;
172 const source = yield* permissions.get(origin);
173 const target = yield* permissions.get(destination);
174 const allowed = write
175 ? source === "read-write" && target === "read-write"
176 : source !== "off" && target !== "off";
177 if (!allowed) return false;
178 for (const entry of [origin, destination]) {
179 if (entry.target._tag !== "SshConnectionTarget") continue;
180 const profiles = yield* Effect.serviceOption(ConnectionProfileStore.ConnectionProfileStore);
181 if (Option.isNone(profiles)) return false;
182 const profile = yield* profiles.value
183 .get(entry.target.connectionId)
184 .pipe(Effect.orElseSucceed(() => Option.none()));
185 const key = gitHubRoutingConnectionKey(entry);
186 if (key === null || key !== gitHubRoutingConnectionKey({ ...entry, profile })) return false;
187 }
188 return true;
189});
190​
191function matchesReference(reference: PullRequestRef, filter: PullRequestRef): boolean {
192 return (
193 reference.projectId === filter.projectId &&
194 reference.repository.toLowerCase() === filter.repository.toLowerCase() &&
195 reference.number === filter.number &&
196 (filter.host === undefined || reference.host?.toLowerCase() === filter.host.toLowerCase())
197 );
199​
200const invalidateTarget = Effect.fn("PullRequestRouting.invalidateTarget")(function* (
201 registry: EnvironmentRegistry.EnvironmentRegistry["Service"],
202 origin: EnvironmentId,
203 target: EnvironmentId,
204 inputs: ReadonlyArray<PullRequestInvalidateInput>,
205) {
206 if (target !== origin && !(yield* routingAllowed(registry, origin, target, false))) return;
207 yield* Effect.forEach(
208 inputs,
209 (input) =>
210 registry.run(target, request(WS_METHODS.pullRequestsInvalidate, input)).pipe(
211 // A stalled reader must not delay the write's answer.
212 Effect.timeoutOption("1 second"),
213 Effect.orElseSucceed(() => undefined),
214 ),
215 { concurrency: 3, discard: true },
216 );
217});
218​
219/**
220 * The origin owns the threads linked to this pull request, but a routed read never reaches it.
221 * Tell it which state the read saw so it checks again.
222 */
223const reportState = (
224 { allowStale: _allowStale, expectedAccountId: _expectedAccountId, ...reference }: PullRequestRef,
225 state: PullRequestState,
226) =>
227 request(WS_METHODS.pullRequestsReportState, { reference, state }).pipe(
228 Effect.timeoutOption("5 seconds"),
229 Effect.ignore,
230 Effect.forkDetach,
231 Effect.asVoid,
232 );
233​
234/** Credentials stay on their environments. Only a verified host and account cross the wire. */
235export function createPullRequestRouter() {
236 const routedRequest = Effect.fn("PullRequestRouting.request")(function* <
237 T extends EnvironmentUnaryRpcTag,
238 >(tag: T, input: EnvironmentRpcInput<T>, sourceRead?: ReturnType<typeof request<T>>) {
239 const source = sourceRead ?? request(tag, input);
240 if (tag === WS_METHODS.pullRequestsInvalidate && isInvalidation(input)) {
241 const result = yield* request(tag, input);
242 const origin = yield* EnvironmentSupervisor.EnvironmentSupervisor;
243 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
244 const used = routedReads.get(registry);
245 const targets = new Map<EnvironmentId, PullRequestRef>();
246 for (const entry of used?.values() ?? []) {
247 if (entry.origin !== origin.target.environmentId) continue;
248 const ref = input.reference;
249 if (ref !== undefined && !matchesReference(entry.reference, ref)) continue;
250 for (const target of entry.targets) targets.set(target, entry.reference);
251 if (input.reference !== undefined)
252 targets.set(origin.target.environmentId, entry.reference);
253 }
254 yield* Effect.forEach(
255 targets,
256 ([target, reference]) =>
257 invalidateTarget(registry, origin.target.environmentId, target, [
258 { ...input, ...(input.reference === undefined ? {} : { reference }) },
259 ]),
260 { concurrency: 4, discard: true },
261 );
262 return result;
263 }
264 if ((!reads.has(tag) && !writes.has(tag)) || !isRef(input)) {
265 return yield* request(tag, input);
266 }
267 const ref = input;
268 const origin = yield* EnvironmentSupervisor.EnvironmentSupervisor;
269 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
270 const entries = yield* SubscriptionRef.get(registry.entries);
271 const sourceEntry = entries.get(origin.target.environmentId);
272 const used = routedReads.get(registry) ?? new Map<string, RoutedRead>();
273 routedReads.set(registry, used);
274 const refKey = encodeKey([
275 origin.target.environmentId,
276 ref.projectId,
277 ref.host?.toLowerCase() ?? null,
278 ref.repository.toLowerCase(),
279 String(ref.number),
280 ]);
281 const invalidateReaders = Effect.suspend(() => {
282 if (!writes.has(tag) || used.size === 0) return Effect.void;
283 const targets = new Map<EnvironmentId, PullRequestRef[]>([
284 [origin.target.environmentId, [ref]],
285 ]);
286 for (const entry of used.values()) {
287 if (entry.origin !== origin.target.environmentId || !matchesReference(entry.reference, ref))
288 continue;
289 for (const target of [...entry.targets, origin.target.environmentId]) {
290 const refs = targets.get(target) ?? [];
291 if (!refs.some((existing) => existing.host === entry.reference.host))
292 refs.push(entry.reference);
293 targets.set(target, refs);
294 }
295 }
296 return Effect.forEach(
297 targets,
298 ([target, refs]) =>
299 invalidateTarget(registry, origin.target.environmentId, target, [
300 ...refs.map((reference) => ({
301 reference,
302 ...(tag === WS_METHODS.pullRequestsSetFilesViewed ? { filesViewedOnly: true } : {}),
303 })),
304 ...(tag === WS_METHODS.pullRequestsSetFilesViewed ? [] : [{}]),
305 ]),
306 { concurrency: 4, discard: true },
307 );
308 });
309 // A failed viewed-files batch may have applied some paths. Other writes invalidate on success.
310 const finish = (operation: ReturnType<typeof request<T>>) =>
311 tag === WS_METHODS.pullRequestsSetFilesViewed
312 ? operation.pipe(Effect.ensuring(invalidateReaders))
313 : operation.pipe(Effect.tap(() => invalidateReaders));
314 const alternatives = [];
315 for (const [id, entry] of entries) {
316 if (id === origin.target.environmentId) continue;
317 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
318 continue;
319 const connected = yield* registry
320 .run(
321 id,
322 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
323 Effect.flatMap((s) => SubscriptionRef.get(s.session)),
324 ),
325 )
326 .pipe(Effect.orElseSucceed(() => Option.none()));
327 if (Option.isNone(connected)) continue;
328 if (tag === WS_METHODS.pullRequestsChecks) {
329 const supported = yield* connected.value.initialConfig.pipe(
330 Effect.map((config) => config.environment.capabilities.pullRequestChecks === true),
331 Effect.timeout("2 seconds"),
332 Effect.catchCause((cause) =>
333 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(false),
334 ),
335 );
336 if (!supported) continue;
337 }
338 alternatives.push({ id, local: isLocal(entry) });
339 }
340 if (alternatives.length === 0) return yield* finish(source);
341​
342 const identityProbe = request(WS_METHODS.pullRequestsRouting, ref).pipe(
343 Effect.timeout("2 seconds"),
344 Effect.catchCause((cause) =>
345 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
346 ),
347 );
348 const identity = yield* reads.has(tag)
349 ? shareMetadataRead(
350 pendingRouting,
351 encodeKey([ref.projectId, ref.host?.toLowerCase() ?? null, ref.repository.toLowerCase()]),
352 identityProbe,
353 )
354 : identityProbe;
355 if (identity === null || identity.provider !== "github") return yield* finish(source);
356​
357 const routedInput = {
358 ...input,
359 host: identity.host,
360 expectedAccountId: identity.accountId,
361 };
362 const guardedSource = sourceRead ?? (yield* Effect.cached(request(tag, routedInput)));
363 const local = alternatives.filter((entry) => entry.local);
364 const remote = alternatives.filter((entry) => !entry.local);
365 const sourceLocal = sourceEntry !== undefined && isLocal(sourceEntry);
366 const candidates = [
367 ...(sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
368 ...local.map((entry) => entry.id),
369 ...(!sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
370 ...remote.map((entry) => entry.id),
371 ...(reads.has(tag) ? [origin.target.environmentId] : []),
372 ];
373 const run = (id: EnvironmentId): ReturnType<typeof request<T>> =>
374 (id === origin.target.environmentId
375 ? guardedSource
376 : registry.run(id, request(tag, routedInput))
377 ).pipe(
378 Effect.tap((result) =>
379 id !== origin.target.environmentId && hasState(result)
380 ? reportState(ref, result.state)
381 : Effect.void,
382 ),
383 Effect.tap(() =>
384 Effect.sync(() => {
385 const entry = used.get(refKey) ?? {
386 origin: origin.target.environmentId,
387 reference: { ...ref, host: identity.host },
388 targets: new Set<EnvironmentId>(),
389 };
390 entry.targets.add(id);
391 if (used.size >= 256 && !used.has(refKey)) {
392 const oldest = used.keys().next().value;
393 if (oldest !== undefined) used.delete(oldest);
394 }
395 used.set(refKey, entry);
396 }),
397 ),
398 Effect.mapError((error) =>
399 isUnregistered(error)
400 ? new EnvironmentRpcUnavailableError({
401 environmentId: id,
402 message: "The environment was removed.",
403 })
404 : error,
405 ),
406 );
407 const visit = (index: number): ReturnType<typeof request<T>> => {
408 const id = candidates[index];
409 if (id === undefined) return guardedSource;
410 return Effect.gen(function* () {
411 if (id !== origin.target.environmentId) {
412 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
413 return yield* visit(index + 1);
414 // An older server would discard expectedAccountId. Verify it implements the guard first.
415 const alternateProbe = request(WS_METHODS.pullRequestsRoutingIdentity, {
416 host: identity.host,
417 }).pipe(
418 Effect.timeout("2 seconds"),
419 Effect.catchCause((cause) =>
420 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
421 ),
422 );
423 const alternate = yield* registry
424 .run(
425 id,
426 reads.has(tag)
427 ? shareMetadataRead(pendingIdentities, identity.host.toLowerCase(), alternateProbe)
428 : alternateProbe,
429 )
430 .pipe(
431 Effect.timeout("2 seconds"),
432 Effect.catchCause((cause) =>
433 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
434 ),
435 );
436 if (
437 alternate === null ||
438 alternate.provider !== "github" ||
439 alternate.host.toLowerCase() !== identity.host.toLowerCase() ||
440 alternate.accountId !== identity.accountId
441 ) {
442 return yield* visit(index + 1);
443 }
444 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
445 return yield* visit(index + 1);
446 }
447 const operation = run(id);
448 return yield* (reads.has(tag) ? operation.pipe(readTimeout(id)) : operation).pipe(
449 Effect.catchIf(
450 (error) =>
451 (reads.has(tag) || rejectedBeforeDispatch(error)) && index + 1 < candidates.length,
452 () => visit(index + 1),
453 ),
454 Effect.map((result) =>
455 typeof result === "object" && result !== null && "projectId" in result
456 ? {
457 ...result,
458 projectId: ref.projectId,
459 ...(tag === WS_METHODS.pullRequestsDetail
460 ? { projectTitle: identity.projectTitle, workspaceRoot: identity.workspaceRoot }
461 : {}),
462 }
463 : result,
464 ),
465 );
466 });
467 };
468 return yield* finish(visit(0));
469 });
470​
471 return Effect.fn("PullRequestRouting.readOrWrite")(function* <T extends EnvironmentUnaryRpcTag>(
472 tag: T,
473 input: EnvironmentRpcInput<T>,
474 ) {
475 if (!reads.has(tag) || !isRef(input)) return yield* routedRequest(tag, input);
476 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
477 const entries = yield* SubscriptionRef.get(registry.entries);
478 if (entries.size < 2) return yield* request(tag, input);
479 const origin = yield* EnvironmentSupervisor.EnvironmentSupervisor;
480 let allowed = false;
481 for (const id of entries.keys()) {
482 if (
483 id !== origin.target.environmentId &&
484 (yield* routingAllowed(registry, origin.target.environmentId, id, false))
485 ) {
486 allowed = true;
487 break;
488 }
489 }
490 if (!allowed) return yield* request(tag, input);
491 const strictInput = { ...input, allowStale: false };
492 const source = yield* Effect.cached(
493 request(tag, strictInput).pipe(readTimeout(origin.target.environmentId)),
494 );
495 const sourceEntry = entries.get(origin.target.environmentId);
496 const routed = routedRequest(tag, strictInput, source);
497 return yield* (
498 sourceEntry !== undefined && isLocal(sourceEntry)
499 ? source.pipe(Effect.catch(() => routed))
500 : routed
501 ).pipe(
502 Effect.catch((error) =>
503 input.allowStale !== false &&
504 (tag === WS_METHODS.pullRequestsSummary || tag === WS_METHODS.pullRequestsDetail)
505 ? request(tag, input)
506 : Effect.fail(error),
507 ),
508 );
509 });