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

pullRequestRouting.ts

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