The best way to control Claude Code, Codex and more from any computer or phone

main
ts 516 lines 20.2 KB
Raw
1 import { msg } from "gt-i18n";
2 import { translatableMessage } from "../errors/translatable.ts";
3 import {
4 WS_METHODS,
5 PullRequestRef,
6 PullRequestInvalidateInput,
7 PullRequestState,
8 type EnvironmentId,
9 type PullRequestRoutingResult,
10 type PullRequestRoutingIdentityResult,
11 } from "@t3tools/contracts";
12 import * as Effect from "effect/Effect";
13 import * as Cause from "effect/Cause";
14 import * as Deferred from "effect/Deferred";
15 import * as Exit from "effect/Exit";
16 import * as Option from "effect/Option";
17 import * as Schema from "effect/Schema";
18 import * as SubscriptionRef from "effect/SubscriptionRef";
19
20 import * as EnvironmentRegistry from "../connection/registry.ts";
21 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
22 import {
23 PullRequestRoutingPermissions,
24 pullRequestRoutingConnectionKey,
25 } from "../connection/pullRequestRoutingPermissions.ts";
26 import type { ConnectionCatalogEntry } from "../connection/catalog.ts";
27 import * as ConnectionProfileStore from "../connection/profileStore.ts";
28 import type { RpcSession } from "../rpc/session.ts";
29 import {
30 requestGuarded as request,
31 EnvironmentRpcUnavailableError,
32 type EnvironmentRpcInput,
33 type EnvironmentUnaryRpcTag,
34 } from "../rpc/client.ts";
35
36 const reads = new Set<string>([
37 WS_METHODS.pullRequestsSummary,
38 WS_METHODS.pullRequestsStack,
39 WS_METHODS.pullRequestsDetail,
40 WS_METHODS.pullRequestsPreview,
41 WS_METHODS.pullRequestsChecks,
42 WS_METHODS.pullRequestsActivity,
43 WS_METHODS.pullRequestsThreadComments,
44 WS_METHODS.pullRequestsDiffFileContents,
45 WS_METHODS.pullRequestsFilesViewed,
46 WS_METHODS.pullRequestsChangeBreakdown,
47 WS_METHODS.pullRequestsReviewerCandidates,
48 WS_METHODS.pullRequestsLabelCandidates,
49 ]);
50 // Review guides are not routed: each server keeps its own, so another server answering would
51 // report none, or start a run nobody on the pull request's own server can see.
52 const writes = new Set<string>([
53 WS_METHODS.pullRequestsSetFilesViewed,
54 WS_METHODS.pullRequestsRunAction,
55 WS_METHODS.pullRequestsUpdate,
56 WS_METHODS.pullRequestsComment,
57 WS_METHODS.pullRequestsUpdateComment,
58 WS_METHODS.pullRequestsSubmitReview,
59 WS_METHODS.pullRequestsReplyToThread,
60 WS_METHODS.pullRequestsSetReaction,
61 WS_METHODS.pullRequestsSetThreadResolution,
62 WS_METHODS.pullRequestsRequestReviewers,
63 WS_METHODS.pullRequestsSetLabels,
64 ]);
65 const isRef = Schema.is(PullRequestRef);
66 const hasState = Schema.is(
67 Schema.Struct({ state: PullRequestState, isDraft: Schema.optional(Schema.Boolean) }),
68 );
69 const isInvalidation = Schema.is(PullRequestInvalidateInput);
70 const readTimeout = (environmentId: EnvironmentId) =>
71 Effect.timeoutOrElse({
72 duration: "30 seconds",
73 orElse: () =>
74 Effect.fail(
75 new EnvironmentRpcUnavailableError({
76 environmentId,
77 ...translatableMessage(msg("The environment did not respond to the PR request.")),
78 }),
79 ),
80 });
81 interface RoutedRead {
82 origin: EnvironmentId;
83 reference: PullRequestRef;
84 targets: Set<EnvironmentId>;
85 }
86 const routedReads = new WeakMap<
87 EnvironmentRegistry.EnvironmentRegistry["Service"],
88 Map<string, RoutedRead>
89 >();
90 const isUnregistered = Schema.is(EnvironmentRegistry.EnvironmentNotRegisteredError);
91 const encodeKey = Schema.encodeSync(
92 Schema.fromJsonString(Schema.Array(Schema.NullOr(Schema.String))),
93 );
94 type PendingMetadata<A> = WeakMap<RpcSession, Map<string, Deferred.Deferred<Exit.Exit<A>>>>;
95 const pendingRouting: PendingMetadata<PullRequestRoutingResult | null> = new WeakMap();
96 const pendingIdentities: PendingMetadata<PullRequestRoutingIdentityResult | null> = new WeakMap();
97
98 function shareMetadataRead<A, R>(
99 pending: PendingMetadata<A>,
100 key: string,
101 probe: Effect.Effect<A, never, R>,
102 ): Effect.Effect<A, never, R | EnvironmentSupervisor.EnvironmentSupervisor> {
103 return Effect.uninterruptibleMask((restore) =>
104 Effect.gen(function* () {
105 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
106 const session = yield* SubscriptionRef.get(supervisor.session);
107 if (Option.isNone(session)) return yield* restore(probe);
108 const entries =
109 pending.get(session.value) ?? new Map<string, Deferred.Deferred<Exit.Exit<A>>>();
110 pending.set(session.value, entries);
111 const existing = entries.get(key);
112 if (existing !== undefined) {
113 const result = yield* restore(Deferred.await(existing));
114 // A cancelled first reader must not cancel the other readers waiting on its probe.
115 return yield* restore(
116 Exit.hasInterrupts(result) ? shareMetadataRead(pending, key, probe) : result,
117 );
118 }
119 const result = Deferred.makeUnsafe<Exit.Exit<A>>();
120 entries.set(key, result);
121 return yield* restore(probe).pipe(
122 Effect.onExit((exit) =>
123 Effect.sync(() => entries.delete(key)).pipe(
124 Effect.andThen(Deferred.succeed(result, exit)),
125 ),
126 ),
127 );
128 }),
129 );
130 }
131
132 function isLocal(entry: ConnectionCatalogEntry): boolean {
133 const url =
134 entry.target._tag === "PrimaryConnectionTarget"
135 ? entry.target.httpBaseUrl
136 : Option.isSome(entry.profile) && entry.profile.value._tag === "BearerConnectionProfile"
137 ? entry.profile.value.httpBaseUrl
138 : undefined;
139 if (url === undefined) return false;
140 try {
141 return ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);
142 } catch {
143 return false;
144 }
145 }
146
147 function rejectedBeforeDispatch(error: unknown): boolean {
148 return (
149 typeof error === "object" &&
150 error !== null &&
151 "_tag" in error &&
152 (error._tag === "EnvironmentRpcUnavailableError" ||
153 error._tag === "EnvironmentNotRegisteredError" ||
154 (error._tag === "PullRequestOperationError" &&
155 "operation" in error &&
156 error.operation === "routeIdentity"))
157 );
158 }
159
160 const routingAllowed = Effect.fn("PullRequestRouting.allowed")(function* (
161 registry: EnvironmentRegistry.EnvironmentRegistry["Service"],
162 originId: EnvironmentId,
163 destinationId: EnvironmentId,
164 write: boolean,
165 ) {
166 const entries = yield* SubscriptionRef.get(registry.entries);
167 const origin = entries.get(originId);
168 const destination = entries.get(destinationId);
169 if (
170 !origin?.enabled ||
171 !destination?.enabled ||
172 origin.unsupportedReason !== undefined ||
173 destination.unsupportedReason !== undefined
174 )
175 return false;
176 const permissions = yield* PullRequestRoutingPermissions;
177 const source = yield* permissions.get(origin);
178 const target = yield* permissions.get(destination);
179 const allowed = write
180 ? source === "read-write" && target === "read-write"
181 : source !== "off" && target !== "off";
182 if (!allowed) return false;
183 for (const entry of [origin, destination]) {
184 if (entry.target._tag !== "SshConnectionTarget") continue;
185 const profiles = yield* Effect.serviceOption(ConnectionProfileStore.ConnectionProfileStore);
186 if (Option.isNone(profiles)) return false;
187 const profile = yield* profiles.value
188 .get(entry.target.connectionId)
189 .pipe(Effect.orElseSucceed(() => Option.none()));
190 const key = pullRequestRoutingConnectionKey(entry);
191 if (key === null || key !== pullRequestRoutingConnectionKey({ ...entry, profile }))
192 return false;
193 }
194 return true;
195 });
196
197 function matchesReference(reference: PullRequestRef, filter: PullRequestRef): boolean {
198 return (
199 reference.projectId === filter.projectId &&
200 reference.repository.toLowerCase() === filter.repository.toLowerCase() &&
201 reference.number === filter.number &&
202 (filter.host === undefined || reference.host?.toLowerCase() === filter.host.toLowerCase())
203 );
204 }
205
206 const invalidateTarget = Effect.fn("PullRequestRouting.invalidateTarget")(function* (
207 registry: EnvironmentRegistry.EnvironmentRegistry["Service"],
208 origin: EnvironmentId,
209 target: EnvironmentId,
210 inputs: ReadonlyArray<PullRequestInvalidateInput>,
211 ) {
212 if (target !== origin && !(yield* routingAllowed(registry, origin, target, false))) return;
213 yield* Effect.forEach(
214 inputs,
215 (input) =>
216 registry.run(target, request(WS_METHODS.pullRequestsInvalidate, input)).pipe(
217 // A stalled reader must not delay the write's answer.
218 Effect.timeoutOption("1 second"),
219 Effect.orElseSucceed(() => undefined),
220 ),
221 { concurrency: 3, discard: true },
222 );
223 });
224
225 /**
226 * The origin owns the threads linked to this pull request, but a routed read never reaches it.
227 * Tell it which state the read saw so it checks again.
228 */
229 const reportState = (
230 { allowStale: _allowStale, expectedAccountId: _expectedAccountId, ...reference }: PullRequestRef,
231 status: { readonly state: PullRequestState; readonly isDraft?: boolean | undefined },
232 ) =>
233 request(WS_METHODS.pullRequestsReportState, {
234 reference,
235 state: status.state,
236 ...(status.isDraft === undefined ? {} : { isDraft: status.isDraft }),
237 }).pipe(Effect.timeoutOption("5 seconds"), Effect.ignore, Effect.forkDetach, Effect.asVoid);
238
239 /** Credentials stay on their environments. Only a verified host and account cross the wire. */
240 export function createPullRequestRouter() {
241 const routedRequest = Effect.fn("PullRequestRouting.request")(function* <
242 T extends EnvironmentUnaryRpcTag,
243 >(tag: T, input: EnvironmentRpcInput<T>, sourceRead?: ReturnType<typeof request<T>>) {
244 const source = sourceRead ?? request(tag, input);
245 if (tag === WS_METHODS.pullRequestsInvalidate && isInvalidation(input)) {
246 const result = yield* request(tag, input);
247 const origin = yield* EnvironmentSupervisor.EnvironmentSupervisor;
248 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
249 const used = routedReads.get(registry);
250 const targets = new Map<EnvironmentId, PullRequestRef>();
251 for (const entry of used?.values() ?? []) {
252 if (entry.origin !== origin.target.environmentId) continue;
253 const ref = input.reference;
254 if (ref !== undefined && !matchesReference(entry.reference, ref)) continue;
255 for (const target of entry.targets) targets.set(target, entry.reference);
256 if (input.reference !== undefined)
257 targets.set(origin.target.environmentId, entry.reference);
258 }
259 yield* Effect.forEach(
260 targets,
261 ([target, reference]) =>
262 invalidateTarget(registry, origin.target.environmentId, target, [
263 { ...input, ...(input.reference === undefined ? {} : { reference }) },
264 ]),
265 { concurrency: 4, discard: true },
266 );
267 return result;
268 }
269 if ((!reads.has(tag) && !writes.has(tag)) || !isRef(input)) {
270 return yield* request(tag, input);
271 }
272 const ref = input;
273 const origin = yield* EnvironmentSupervisor.EnvironmentSupervisor;
274 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
275 const entries = yield* SubscriptionRef.get(registry.entries);
276 const sourceEntry = entries.get(origin.target.environmentId);
277 const used = routedReads.get(registry) ?? new Map<string, RoutedRead>();
278 routedReads.set(registry, used);
279 const refKey = encodeKey([
280 origin.target.environmentId,
281 ref.projectId,
282 ref.host?.toLowerCase() ?? null,
283 ref.repository.toLowerCase(),
284 String(ref.number),
285 ]);
286 const invalidateReaders = Effect.suspend(() => {
287 if (!writes.has(tag) || used.size === 0) return Effect.void;
288 const targets = new Map<EnvironmentId, PullRequestRef[]>([
289 [origin.target.environmentId, [ref]],
290 ]);
291 for (const entry of used.values()) {
292 if (entry.origin !== origin.target.environmentId || !matchesReference(entry.reference, ref))
293 continue;
294 for (const target of [...entry.targets, origin.target.environmentId]) {
295 const refs = targets.get(target) ?? [];
296 if (!refs.some((existing) => existing.host === entry.reference.host))
297 refs.push(entry.reference);
298 targets.set(target, refs);
299 }
300 }
301 return Effect.forEach(
302 targets,
303 ([target, refs]) =>
304 invalidateTarget(registry, origin.target.environmentId, target, [
305 ...refs.map((reference) => ({
306 reference,
307 ...(tag === WS_METHODS.pullRequestsSetFilesViewed ? { filesViewedOnly: true } : {}),
308 })),
309 ...(tag === WS_METHODS.pullRequestsSetFilesViewed ? [] : [{}]),
310 ]),
311 { concurrency: 4, discard: true },
312 );
313 });
314 // A failed viewed-files batch may have applied some paths. Other writes invalidate on success.
315 const finish = (operation: ReturnType<typeof request<T>>) =>
316 tag === WS_METHODS.pullRequestsSetFilesViewed
317 ? operation.pipe(Effect.ensuring(invalidateReaders))
318 : operation.pipe(Effect.tap(() => invalidateReaders));
319 const alternatives = [];
320 for (const [id, entry] of entries) {
321 if (id === origin.target.environmentId) continue;
322 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
323 continue;
324 const connected = yield* registry
325 .run(
326 id,
327 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
328 Effect.flatMap((s) => SubscriptionRef.get(s.session)),
329 ),
330 )
331 .pipe(Effect.orElseSucceed(() => Option.none()));
332 if (Option.isNone(connected)) continue;
333 if (tag === WS_METHODS.pullRequestsChecks) {
334 const supported = yield* connected.value.initialConfig.pipe(
335 Effect.map((config) => config.environment.capabilities.pullRequestChecks === true),
336 Effect.timeout("2 seconds"),
337 Effect.catchCause((cause) =>
338 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(false),
339 ),
340 );
341 if (!supported) continue;
342 }
343 alternatives.push({ id, local: isLocal(entry) });
344 }
345 if (alternatives.length === 0) return yield* finish(source);
346
347 const identityProbe = request(WS_METHODS.pullRequestsRouting, ref).pipe(
348 Effect.timeout("2 seconds"),
349 Effect.catchCause((cause) =>
350 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
351 ),
352 );
353 const identity = yield* reads.has(tag)
354 ? shareMetadataRead(
355 pendingRouting,
356 encodeKey([ref.projectId, ref.host?.toLowerCase() ?? null, ref.repository.toLowerCase()]),
357 identityProbe,
358 )
359 : identityProbe;
360 // The source server answers only for a host whose account it can verify.
361 if (identity === null) return yield* finish(source);
362
363 const routedInput = {
364 ...input,
365 host: identity.host,
366 expectedAccountId: identity.accountId,
367 };
368 const guardedSource = sourceRead ?? (yield* Effect.cached(request(tag, routedInput)));
369 const local = alternatives.filter((entry) => entry.local);
370 const remote = alternatives.filter((entry) => !entry.local);
371 const sourceLocal = sourceEntry !== undefined && isLocal(sourceEntry);
372 const candidates = [
373 ...(sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
374 ...local.map((entry) => entry.id),
375 ...(!sourceLocal && writes.has(tag) ? [origin.target.environmentId] : []),
376 ...remote.map((entry) => entry.id),
377 ...(reads.has(tag) ? [origin.target.environmentId] : []),
378 ];
379 const run = (id: EnvironmentId): ReturnType<typeof request<T>> =>
380 (id === origin.target.environmentId
381 ? guardedSource
382 : registry.run(id, request(tag, routedInput))
383 ).pipe(
384 Effect.tap((result) =>
385 id !== origin.target.environmentId && hasState(result)
386 ? reportState(ref, result)
387 : Effect.void,
388 ),
389 Effect.tap(() =>
390 Effect.sync(() => {
391 const entry = used.get(refKey) ?? {
392 origin: origin.target.environmentId,
393 reference: { ...ref, host: identity.host },
394 targets: new Set<EnvironmentId>(),
395 };
396 entry.targets.add(id);
397 if (used.size >= 256 && !used.has(refKey)) {
398 const oldest = used.keys().next().value;
399 if (oldest !== undefined) used.delete(oldest);
400 }
401 used.set(refKey, entry);
402 }),
403 ),
404 Effect.mapError((error) =>
405 isUnregistered(error)
406 ? new EnvironmentRpcUnavailableError({
407 environmentId: id,
408 ...translatableMessage(msg("The environment was removed.")),
409 })
410 : error,
411 ),
412 );
413 const visit = (index: number): ReturnType<typeof request<T>> => {
414 const id = candidates[index];
415 if (id === undefined) return guardedSource;
416 return Effect.gen(function* () {
417 if (id !== origin.target.environmentId) {
418 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
419 return yield* visit(index + 1);
420 // An older server would discard expectedAccountId. Verify it implements the guard first.
421 const alternateProbe = request(WS_METHODS.pullRequestsRoutingIdentity, {
422 host: identity.host,
423 }).pipe(
424 Effect.timeout("2 seconds"),
425 Effect.catchCause((cause) =>
426 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
427 ),
428 );
429 const alternate = yield* registry
430 .run(
431 id,
432 reads.has(tag)
433 ? shareMetadataRead(pendingIdentities, identity.host.toLowerCase(), alternateProbe)
434 : alternateProbe,
435 )
436 .pipe(
437 Effect.timeout("2 seconds"),
438 Effect.catchCause((cause) =>
439 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(null),
440 ),
441 );
442 if (
443 alternate === null ||
444 alternate.provider !== identity.provider ||
445 alternate.host.toLowerCase() !== identity.host.toLowerCase() ||
446 alternate.accountId !== identity.accountId
447 ) {
448 return yield* visit(index + 1);
449 }
450 if (!(yield* routingAllowed(registry, origin.target.environmentId, id, writes.has(tag))))
451 return yield* visit(index + 1);
452 }
453 const operation = run(id);
454 return yield* (reads.has(tag) ? operation.pipe(readTimeout(id)) : operation).pipe(
455 Effect.catchIf(
456 (error) =>
457 (reads.has(tag) || rejectedBeforeDispatch(error)) && index + 1 < candidates.length,
458 () => visit(index + 1),
459 ),
460 Effect.map((result) =>
461 typeof result === "object" && result !== null && "projectId" in result
462 ? {
463 ...result,
464 projectId: ref.projectId,
465 ...(tag === WS_METHODS.pullRequestsDetail
466 ? { projectTitle: identity.projectTitle, workspaceRoot: identity.workspaceRoot }
467 : {}),
468 }
469 : result,
470 ),
471 );
472 });
473 };
474 return yield* finish(visit(0));
475 });
476
477 return Effect.fn("PullRequestRouting.readOrWrite")(function* <T extends EnvironmentUnaryRpcTag>(
478 tag: T,
479 input: EnvironmentRpcInput<T>,
480 ) {
481 if (!reads.has(tag) || !isRef(input)) return yield* routedRequest(tag, input);
482 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
483 const entries = yield* SubscriptionRef.get(registry.entries);
484 if (entries.size < 2) return yield* request(tag, input);
485 const origin = yield* EnvironmentSupervisor.EnvironmentSupervisor;
486 let allowed = false;
487 for (const id of entries.keys()) {
488 if (
489 id !== origin.target.environmentId &&
490 (yield* routingAllowed(registry, origin.target.environmentId, id, false))
491 ) {
492 allowed = true;
493 break;
494 }
495 }
496 if (!allowed) return yield* request(tag, input);
497 const strictInput = { ...input, allowStale: false };
498 const source = yield* Effect.cached(
499 request(tag, strictInput).pipe(readTimeout(origin.target.environmentId)),
500 );
501 const sourceEntry = entries.get(origin.target.environmentId);
502 const routed = routedRequest(tag, strictInput, source);
503 return yield* (
504 sourceEntry !== undefined && isLocal(sourceEntry)
505 ? source.pipe(Effect.catch(() => routed))
506 : routed
507 ).pipe(
508 Effect.catch((error) =>
509 input.allowStale !== false &&
510 (tag === WS_METHODS.pullRequestsSummary || tag === WS_METHODS.pullRequestsDetail)
511 ? request(tag, input)
512 : Effect.fail(error),
513 ),
514 );
515 });
516 }