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