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