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

pullRequestRouting.ts

504 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 // A stalled reader must not delay the write's answer.
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 invalidateReaders = Effect.suspend(() => {
276 if (!writes.has(tag) || used.size === 0) return Effect.void;
277 const targets = new Map<EnvironmentId, PullRequestRef[]>([
278 [origin.target.environmentId, [ref]],
279 ]);
280 for (const entry of used.values()) {
281 if (entry.origin !== origin.target.environmentId || !matchesReference(entry.reference, ref))
282 continue;
283 for (const target of [...entry.targets, origin.target.environmentId]) {
284 const refs = targets.get(target) ?? [];
285 if (!refs.some((existing) => existing.host === entry.reference.host))
286 refs.push(entry.reference);
287 targets.set(target, refs);
288 }
289 }
290 return Effect.forEach(
291 targets,
292 ([target, refs]) =>
293 invalidateTarget(registry, origin.target.environmentId, target, [
294 ...refs.map((reference) => ({
295 reference,
296 ...(tag === WS_METHODS.pullRequestsSetFilesViewed ? { filesViewedOnly: true } : {}),
297 })),
298 ...(tag === WS_METHODS.pullRequestsSetFilesViewed ? [] : [{}]),
299 ]),
300 { concurrency: 4, discard: true },
301 );
302 });
303 // A failed viewed-files batch may have applied some paths. Other writes invalidate on success.
304 const finish = (operation: ReturnType<typeof request<T>>) =>
305 tag === WS_METHODS.pullRequestsSetFilesViewed
306 ? operation.pipe(Effect.ensuring(invalidateReaders))
307 : operation.pipe(Effect.tap(() => invalidateReaders));
308 const alternatives = [];
309 for (const [id, entry] of entries) {
310 if (id === origin.target.environmentId) continue;
311 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
312 continue;
313 const connected = yield* registry
314 .run(
315 id,
316 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
317 Effect.flatMap((s) => SubscriptionRef.get(s.session)),
318 ),
319 )
320 .pipe(Effect.orElseSucceed(() => Option.none()));
321 if (Option.isNone(connected)) continue;
322 if (tag === WS_METHODS.pullRequestsChecks) {
323 const supported = yield* connected.value.initialConfig.pipe(
324 Effect.map((config) => config.environment.capabilities.pullRequestChecks === true),
325 Effect.timeout("2 seconds"),
326 Effect.catchCause((cause) =>
327 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(false),
328 ),
329 );
330 if (!supported) continue;
331 }
332 alternatives.push({ id, local: isLocal(entry) });
333 }
334 if (alternatives.length === 0) return yield* finish(source);
335​
336 const identityProbe = request(WS_METHODS.pullRequestsRouting, ref).pipe(
337 Effect.timeout("2 seconds"),
338 Effect.catchCause((cause) =>
339 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
340 ),
341 );
342 const identity = yield* reads.has(tag)
343 ? shareMetadataRead(
344 pendingRouting,
345 encodeKey([ref.projectId, ref.host?.toLowerCase() ?? null, ref.repository.toLowerCase()]),
346 identityProbe,
347 )
348 : identityProbe;
349 if (identity === null || identity.provider !== "github") return yield* finish(source);
350​
351 const routedInput = {
352 ...input,
353 host: identity.host,
354 expectedAccountId: identity.accountId,
355 };
356 const guardedSource = sourceRead ?? (yield* Effect.cached(request(tag, routedInput)));
357 const local = alternatives.filter((entry) => entry.local);
358 const remote = alternatives.filter((entry) => !entry.local);
359 const sourceLocal = sourceEntry !== undefined && isLocal(sourceEntry);
360 const candidates = [
361 ...(sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
362 ...local.map((entry) => entry.id),
363 ...(!sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
364 ...remote.map((entry) => entry.id),
365 ...(reads.has(tag) ? [origin.target.environmentId] : []),
366 ];
367 const run = (id: EnvironmentId): ReturnType<typeof request<T>> =>
368 (id === origin.target.environmentId
369 ? guardedSource
370 : registry.run(id, request(tag, routedInput))
371 ).pipe(
372 Effect.tap((result) =>
373 id !== origin.target.environmentId && hasState(result)
374 ? reportState(ref, result.state)
375 : Effect.void,
376 ),
377 Effect.tap(() =>
378 Effect.sync(() => {
379 const entry = used.get(refKey) ?? {
380 origin: origin.target.environmentId,
381 reference: { ...ref, host: identity.host },
382 targets: new Set<EnvironmentId>(),
383 };
384 entry.targets.add(id);
385 if (used.size >= 256 && !used.has(refKey)) {
386 const oldest = used.keys().next().value;
387 if (oldest !== undefined) used.delete(oldest);
388 }
389 used.set(refKey, entry);
390 }),
391 ),
392 Effect.mapError((error) =>
393 isUnregistered(error)
394 ? new EnvironmentRpcUnavailableError({
395 environmentId: id,
396 message: "The environment was removed.",
397 })
398 : error,
399 ),
400 );
401 const visit = (index: number): ReturnType<typeof request<T>> => {
402 const id = candidates[index];
403 if (id === undefined) return guardedSource;
404 return Effect.gen(function* () {
405 if (id !== origin.target.environmentId) {
406 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
407 return yield* visit(index + 1);
408 // An older server would discard expectedAccountId. Verify it implements the guard first.
409 const alternateProbe = request(WS_METHODS.pullRequestsRoutingIdentity, {
410 host: identity.host,
411 }).pipe(
412 Effect.timeout("2 seconds"),
413 Effect.catchCause((cause) =>
414 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
415 ),
416 );
417 const alternate = yield* registry
418 .run(
419 id,
420 reads.has(tag)
421 ? shareMetadataRead(pendingIdentities, identity.host.toLowerCase(), alternateProbe)
422 : alternateProbe,
423 )
424 .pipe(
425 Effect.timeout("2 seconds"),
426 Effect.catchCause((cause) =>
427 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
428 ),
429 );
430 if (
431 alternate === null ||
432 alternate.provider !== "github" ||
433 alternate.host.toLowerCase() !== identity.host.toLowerCase() ||
434 alternate.accountId !== identity.accountId
435 ) {
436 return yield* visit(index + 1);
437 }
438 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
439 return yield* visit(index + 1);
440 }
441 const operation = run(id);
442 return yield* (reads.has(tag) ? operation.pipe(readTimeout(id)) : operation).pipe(
443 Effect.catchIf(
444 (error) =>
445 (reads.has(tag) || rejectedBeforeDispatch(error)) && index + 1 < candidates.length,
446 () => visit(index + 1),
447 ),
448 Effect.map((result) =>
449 typeof result === "object" && result !== null && "projectId" in result
450 ? {
451 ...result,
452 projectId: ref.projectId,
453 ...(tag === WS_METHODS.pullRequestsDetail
454 ? { projectTitle: identity.projectTitle, workspaceRoot: identity.workspaceRoot }
455 : {}),
456 }
457 : result,
458 ),
459 );
460 });
461 };
462 return yield* finish(visit(0));
463 });
464​
465 return Effect.fn("PullRequestRouting.readOrWrite")(function* <T extends EnvironmentUnaryRpcTag>(
466 tag: T,
467 input: EnvironmentRpcInput<T>,
468 ) {
469 if (!reads.has(tag) || !isRef(input)) return yield* routedRequest(tag, input);
470 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
471 const entries = yield* SubscriptionRef.get(registry.entries);
472 if (entries.size < 2) return yield* request(tag, input);
473 const origin = yield* EnvironmentSupervisor.EnvironmentSupervisor;
474 let allowed = false;
475 for (const id of entries.keys()) {
476 if (
477 id !== origin.target.environmentId &&
478 (yield* routingAllowed(registry, origin.target.environmentId, id, false))
479 ) {
480 allowed = true;
481 break;
482 }
483 }
484 if (!allowed) return yield* request(tag, input);
485 const strictInput = { ...input, allowStale: false };
486 const source = yield* Effect.cached(
487 request(tag, strictInput).pipe(readTimeout(origin.target.environmentId)),
488 );
489 const sourceEntry = entries.get(origin.target.environmentId);
490 const routed = routedRequest(tag, strictInput, source);
491 return yield* (
492 sourceEntry !== undefined && isLocal(sourceEntry)
493 ? source.pipe(Effect.catch(() => routed))
494 : routed
495 ).pipe(
496 Effect.catch((error) =>
497 input.allowStale !== false &&
498 (tag === WS_METHODS.pullRequestsSummary || tag === WS_METHODS.pullRequestsDetail)
499 ? request(tag, input)
500 : Effect.fail(error),
501 ),
502 );
503 });