Open History to see the last commit
1import {
2 type AuthMcpClientAccess,
3 type EnvironmentId,
4 type PeerLinkCreateInput,
5 type PeerLinkFailureKind,
6 type PeerLinkSummary,
7 peerLinkFailureKind,
8} from "@t3tools/contracts";
9import * as Result from "effect/Result";
10import { mFallback, msg } from "gt-i18n";
11import type { M } from "gt-i18n";
12
13import type { LinkableMachine } from "./linkRequest.ts";
14
15/** Pairings a batch opens at once, so a fleet is not signed in to all at the same moment. */
16const LINK_BATCH_CONCURRENCY = 4;
17
18/**
19 * Why a batch cannot link a machine: the client mints each pairing code there
20 * with its own session, and sends it only to addresses it already has for it.
21 */
22export type LinkBatchBlock =
23 | "links_unknown"
24 | "linked"
25 | "not_connected"
26 | "no_access"
27 | "no_address";
28
29/** Whether the linking environment's own links are known yet. */
30export type LinkListState = "loading" | "failed" | "loaded";
31
32export const linkListState = (query: {
33 readonly data: unknown;
34 readonly error: unknown;
35}): LinkListState => (query.data !== null ? "loaded" : query.error !== null ? "failed" : "loading");
36
37export interface LinkBatchCandidate {
38 readonly machine: LinkableMachine;
39 readonly blocked: LinkBatchBlock | null;
40}
41
42/**
43 * `writable` holds the machines where this client's session may create pairing codes.
44 * Until `links` has loaded, no machine's `linked` is known, and linking one that is
45 * already linked would replace its working token, so none is offered.
46 */
47export const linkBatchCandidates = (
48 machines: ReadonlyArray<LinkableMachine>,
49 writable: ReadonlySet<EnvironmentId>,
50 links: LinkListState,
51): ReadonlyArray<LinkBatchCandidate> =>
52 machines.map((machine) => ({
53 machine,
54 blocked:
55 links !== "loaded"
56 ? "links_unknown"
57 : machine.linked
58 ? "linked"
59 : !machine.connected
60 ? "not_connected"
61 : !writable.has(machine.environmentId)
62 ? "no_access"
63 : machine.urls.length === 0
64 ? "no_address"
65 : null,
66 }));
67
68export const linkBatchBlockLabel = (blocked: LinkBatchBlock, resolve: M = mFallback): string => {
69 switch (blocked) {
70 case "links_unknown":
71 return resolve(msg("Not known yet whether it is linked"));
72 case "linked":
73 return resolve(msg("Already linked"));
74 case "not_connected":
75 return resolve(msg("This app is not connected to it"));
76 case "no_access":
77 return resolve(msg("Your session there cannot create pairing codes"));
78 case "no_address":
79 return resolve(msg("No address another machine can reach"));
80 }
81};
82
83/** Why the link back, from the linked machine to the linking one, is not offered. */
84export type LinkBackBlock =
85 | "target_links_off"
86 | "target_no_access"
87 | "source_no_access"
88 | "source_no_address";
89
90/**
91 * `hidden`: the user would not expect it, so nothing is shown. `blocked`: both machines are
92 * the user's own connected environments, so one line says what is in the way.
93 */
94export type LinkBackOffer =
95 | { readonly kind: "offered" }
96 | { readonly kind: "blocked"; readonly reason: LinkBackBlock }
97 | { readonly kind: "hidden" };
98
99/**
100 * Whether linking `source` to `target` can also link `target` back with no pasted code. The
101 * reverse is an ordinary link made on the target: the client creates it there and mints its
102 * pairing code on the source, each with its own session, at an address it has for the source.
103 */
104export const linkBackOffer = (input: {
105 /** Null for a machine the client has not saved, such as a typed address. */
106 readonly target: {
107 readonly connected: boolean;
108 /** Linked environments is supported and switched on there. */
109 readonly offersLinks: boolean;
110 /** The client's session there may create links: `access:write`. */
111 readonly writable: boolean;
112 /** Its own links: null until they are known. */
113 readonly links: ReadonlyArray<Pick<PeerLinkSummary, "environmentId" | "status">> | null;
114 } | null;
115 readonly source: {
116 readonly environmentId: EnvironmentId;
117 readonly connected: boolean;
118 /** The client's session there may create pairing codes: `access:write`. */
119 readonly writable: boolean;
120 readonly urls: ReadonlyArray<string>;
121 };
122}): LinkBackOffer => {
123 const { target, source } = input;
124 if (target === null || !target.connected || !source.connected) return { kind: "hidden" };
125 if (!target.offersLinks) return { kind: "blocked", reason: "target_links_off" };
126 if (!target.writable) return { kind: "blocked", reason: "target_no_access" };
127 if (!source.writable) return { kind: "blocked", reason: "source_no_access" };
128 if (source.urls.length === 0) return { kind: "blocked", reason: "source_no_address" };
129 // Unknown or already there: offering it could replace a working token.
130 if (
131 target.links === null ||
132 target.links.some(
133 (link) => link.environmentId === source.environmentId && link.status !== "expired",
134 )
135 ) {
136 return { kind: "hidden" };
137 }
138 return { kind: "offered" };
139};
140
141export const linkBackBlockLabel = (
142 blocked: LinkBackBlock,
143 names: { readonly source: string; readonly target: string },
144 resolve: M = mFallback,
145): string => {
146 switch (blocked) {
147 case "target_links_off":
148 return resolve(
149 msg`${{ target: names.target }} cannot link back: Linked environments is off there.`,
150 );
151 case "target_no_access":
152 return resolve(
153 msg`${{ target: names.target }} cannot link back: your session there cannot create links.`,
154 );
155 case "source_no_access":
156 return resolve(
157 msg`${{ target: names.target }} cannot link back: your session on ${{ source: names.source }} cannot create pairing codes.`,
158 );
159 case "source_no_address":
160 return resolve(
161 msg`${{ target: names.target }} cannot link back: this app has no address for ${{ source: names.source }} it can reach.`,
162 );
163 }
164};
165
166export type LinkBatchFailure = PeerLinkFailureKind | "no_code";
167
168export type LinkAttemptOutcome =
169 | { readonly kind: "linked" }
170 | { readonly kind: "failed"; readonly failure: LinkBatchFailure; readonly detail: string | null };
171
172/** `back` is set when the link back was asked for: it never changes how the link itself went. */
173export type LinkBatchOutcome =
174 | { readonly kind: "linked"; readonly back?: LinkAttemptOutcome }
175 | { readonly kind: "failed"; readonly failure: LinkBatchFailure; readonly detail: string | null };
176
177export const linkBatchFailureLabel = (
178 failure: LinkBatchFailure,
179 resolve: M = mFallback,
180): string => {
181 switch (failure) {
182 case "unreachable":
183 return resolve(msg("Unreachable"));
184 case "code_refused":
185 return resolve(msg("Pairing code refused"));
186 case "wrong_environment":
187 return resolve(msg("Another environment answered"));
188 case "no_code":
189 return resolve(msg("Could not get a pairing code there"));
190 case "other":
191 return resolve(msg("Could not link"));
192 }
193};
194
195/**
196 * Only the linking environment's own error passes its message through:
197 * anything else may carry the request, and with it the pairing code.
198 */
199const linkFailure = (failure: unknown): LinkAttemptOutcome & { readonly kind: "failed" } => {
200 if (
201 typeof failure === "object" &&
202 failure !== null &&
203 "_tag" in failure &&
204 failure._tag === "PeerLinkError" &&
205 "reason" in failure &&
206 "message" in failure &&
207 typeof failure.message === "string"
208 ) {
209 const error = failure as unknown as Parameters<typeof peerLinkFailureKind>[0];
210 return { kind: "failed", failure: peerLinkFailureKind(error), detail: failure.message };
211 }
212 return { kind: "failed", failure: "other", detail: null };
213};
214
215type BatchMachine = Pick<LinkableMachine, "environmentId" | "label" | "urls">;
216
217type MintPairingCode = (
218 environmentId: EnvironmentId,
219 access: AuthMcpClientAccess,
220) => Promise<Result.Result<string, unknown>>;
221
222/**
223 * One link to `machine`: a one-use code minted there with the client's session, handed to
224 * `link` with the addresses the client has for it. The code stays in this call.
225 */
226export async function linkWithMintedCode(input: {
227 readonly machine: BatchMachine;
228 readonly access: AuthMcpClientAccess;
229 readonly mint: MintPairingCode;
230 readonly link: (input: PeerLinkCreateInput) => Promise<Result.Result<unknown, unknown>>;
231}): Promise<LinkAttemptOutcome> {
232 const { machine } = input;
233 const [url, ...alternateUrls] = machine.urls;
234 if (url === undefined) return { kind: "failed", failure: "unreachable", detail: null };
235 try {
236 const minted = await input.mint(machine.environmentId, input.access);
237 if (Result.isFailure(minted)) return { kind: "failed", failure: "no_code", detail: null };
238 const linked = await input.link({
239 url,
240 ...(alternateUrls.length > 0 ? { alternateUrls } : {}),
241 expectedEnvironmentId: machine.environmentId,
242 expectedLabel: machine.label,
243 pairingCode: minted.success,
244 access: input.access,
245 });
246 return Result.isSuccess(linked) ? { kind: "linked" } : linkFailure(linked.failure);
247 } catch {
248 return { kind: "failed", failure: "other", detail: null };
249 }
250}
251
252/**
253 * Links each machine as a single link is made: a one-use code minted on that
254 * machine with the client's session there, then handed to the linking
255 * environment with the addresses the client has for it. A failure stops only
256 * its own machine. Codes stay in this call and are never reported.
257 */
258export async function runLinkBatch(input: {
259 readonly machines: ReadonlyArray<BatchMachine>;
260 readonly access: AuthMcpClientAccess;
261 readonly mint: MintPairingCode;
262 readonly link: (input: PeerLinkCreateInput) => Promise<Result.Result<unknown, unknown>>;
263 /**
264 * Also links each of `targets` back to `source` once its own link is made. `link` creates
265 * the link on that machine. A failure here is reported beside the link it follows.
266 */
267 readonly back?: {
268 readonly source: BatchMachine;
269 readonly targets: ReadonlySet<EnvironmentId>;
270 readonly link: (
271 environmentId: EnvironmentId,
272 input: PeerLinkCreateInput,
273 ) => Promise<Result.Result<unknown, unknown>>;
274 };
275 /** Called once, at the end: listing probes every linked machine, so `link` must not refresh. */
276 readonly refreshLinks: () => void;
277 readonly onOutcome?: (environmentId: EnvironmentId, outcome: LinkBatchOutcome) => void;
278}): Promise<ReadonlyMap<EnvironmentId, LinkBatchOutcome>> {
279 const outcomes = new Map<EnvironmentId, LinkBatchOutcome>();
280 const { access, mint, back } = input;
281 const linkOne = async (machine: BatchMachine): Promise<LinkBatchOutcome> => {
282 const outcome = await linkWithMintedCode({ machine, access, mint, link: input.link });
283 if (outcome.kind !== "linked" || !back?.targets.has(machine.environmentId)) return outcome;
284 return {
285 kind: "linked",
286 back: await linkWithMintedCode({
287 machine: back.source,
288 access,
289 mint,
290 link: (create) => back.link(machine.environmentId, create),
291 }),
292 };
293 };
294 const queue = [...input.machines];
295 const worker = async () => {
296 for (let machine = queue.shift(); machine !== undefined; machine = queue.shift()) {
297 const outcome = await linkOne(machine);
298 outcomes.set(machine.environmentId, outcome);
299 input.onOutcome?.(machine.environmentId, outcome);
300 }
301 };
302 await Promise.all(Array.from({ length: LINK_BATCH_CONCURRENCY }, worker));
303 if ([...outcomes.values()].some((outcome) => outcome.kind === "linked")) input.refreshLinks();
304 return outcomes;
305}
306
307/** How a batch went, and the machines a retry would run again. */
308export const linkBatchSummary = (outcomes: ReadonlyMap<EnvironmentId, LinkBatchOutcome>) => {
309 const failed = [...outcomes].flatMap(([environmentId, outcome]) =>
310 outcome.kind === "failed" ? [environmentId] : [],
311 );
312 return { linked: outcomes.size - failed.length, failed };
313};