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

pullRequestRouting.ts

399 lines15.3 KB

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