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