Open History to see the last commit
1import {
2 AuthMcpClientAccess,
3 AuthMcpRegistrationError,
4 AuthMcpTokenError,
5 EnvironmentHttpApi,
6 EnvironmentId,
7 type ExecutionEnvironmentCapabilities,
8 MCP_PEER_LINK_SOFTWARE_ID,
9 type PeerLink,
10 type PeerLinkCreateInput,
11 PeerLinkError,
12 type PeerLinkSummary,
13} from "@t3tools/contracts";
14import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
15import * as Context from "effect/Context";
16import * as Digest from "effect/crypto/Digest";
17import * as SecureRandom from "effect/crypto/SecureRandom";
18import * as DateTime from "effect/DateTime";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as Base64Url from "effect/encoding/Base64Url";
22import * as Hex from "effect/encoding/Hex";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Redacted from "effect/Redacted";
26import * as Result from "effect/Result";
27import * as Schema from "effect/Schema";
28import * as SqlClient from "effect/sql/SqlClient";
29import * as FetchHttpClient from "effect/http/FetchHttpClient";
30import * as HttpClient from "effect/http/HttpClient";
31import * as HttpApi from "effect/http-api/HttpApi";
32import * as HttpApiClient from "effect/http-api/HttpApiClient";
33import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification";
34
35import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
36import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
37import * as ServerSettings from "../serverSettings.ts";
38
39const PeerHttpApi = HttpApi.make(EnvironmentHttpApi.identifier)
40 .add(EnvironmentHttpApi.groups.metadata)
41 .add(EnvironmentHttpApi.groups.mcpOAuth)
42 .annotateMerge(EnvironmentHttpApi.annotations);
43
44/** The redirect registered for a link. Nothing ever listens there: the code comes back in the response. */
45const LINK_REDIRECT_URI = "http://127.0.0.1/t3code-peer-link";
46/**
47 * How long a peer's descriptor may take before a route counts as unreachable.
48 * A tailnet or relayed route to a machine that is waking up takes longer.
49 */
50const probeTimeout = (origin: string) =>
51 isLocalLoopbackHost(new URL(origin).hostname) ? Duration.seconds(3) : Duration.seconds(10);
52
53/** A usable link: where to reach the peer and the token to send there. */
54export interface ResolvedPeerLink {
55 readonly link: PeerLink;
56 /** The first address that answered as this peer. */
57 readonly url: string;
58 readonly token: string;
59}
60
61export const LINKED_ENVIRONMENTS_OFF =
62 "Linked environments is off on this machine. Turn it on in Settings → Labs.";
63
64/**
65 * Links from this environment to others. Linking signs this environment in to
66 * the peer's `/mcp` as an outside agent with a pairing code from the peer, the
67 * same MCP OAuth flow an outside agent uses, without a browser. The peer's
68 * session token is kept in the server secret store; the table keeps the rest.
69 */
70export class PeerLinks extends Context.Service<
71 PeerLinks,
72 {
73 /** Whether the Linked environments beta (Settings → Labs) is on here. */
74 readonly enabled: Effect.Effect<boolean>;
75 readonly link: (input: PeerLinkCreateInput) => Effect.Effect<PeerLink, PeerLinkError>;
76 /**
77 * The environment answering at `url`, or nothing when it is not a usable
78 * address or does not answer as T3 Code. Sends no credential.
79 */
80 readonly describe: (
81 url: string,
82 ) => Effect.Effect<
83 Option.Option<{ readonly environmentId: EnvironmentId; readonly label: string }>
84 >;
85 readonly list: Effect.Effect<ReadonlyArray<PeerLinkSummary>, PeerLinkError>;
86 /** The stored link, without asking the peer whether it answers. */
87 readonly get: (
88 environmentId: EnvironmentId,
89 ) => Effect.Effect<Option.Option<PeerLink>, PeerLinkError>;
90 /** Forgets the link here. The peer still lists the session until it is revoked there. */
91 readonly unlink: (environmentId: EnvironmentId) => Effect.Effect<boolean, PeerLinkError>;
92 /** An address that answers as the linked peer, with its token, ready to call. */
93 readonly resolve: (
94 environmentId: EnvironmentId,
95 ) => Effect.Effect<ResolvedPeerLink, PeerLinkError>;
96 /** Records the outcome of a call, so listing shows whether the peer answered last time. */
97 readonly recordOutcome: (
98 environmentId: EnvironmentId,
99 outcome: { readonly error: string | null },
100 ) => Effect.Effect<void>;
101 }
102>()("t3/peer/PeerLinks") {}
103
104interface PeerLinkRow {
105 readonly environment_id: string;
106 readonly secret_name: string;
107 readonly label: string;
108 readonly urls_json: string;
109 readonly access: string;
110 readonly linked_at: string;
111 readonly expires_at: string;
112 readonly last_reached_at: string | null;
113 readonly last_error: string | null;
114 readonly fenced: number;
115}
116
117const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
118const encodeUrls = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
119const decodeAccess = Schema.decodeUnknownEffect(AuthMcpClientAccess);
120
121/** Fails with a fixed storage error that keeps its cause; the log gets the details. */
122const failStorage = (cause: unknown) =>
123 Effect.logWarning("Peer link storage failed", cause).pipe(
124 Effect.andThen(
125 Effect.fail(
126 new PeerLinkError({
127 reason: "storage",
128 message:
129 "Linked environments could not be read or saved here. The server log has details.",
130 cause,
131 }),
132 ),
133 ),
134 );
135
136/**
137 * The base URL a peer is reached at, normalised to its origin. The pairing
138 * code and then the link's token travel to it, so plain http is accepted only
139 * where the network already encrypts: this machine, or a Tailscale address.
140 */
141const peerOrigin = (url: string) => {
142 const parsed = URL.parse(url);
143 if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) {
144 return Effect.fail(
145 new PeerLinkError({
146 reason: "unreachable",
147 message: `${url} is not an http or https address.`,
148 }),
149 );
150 }
151 if (
152 parsed.protocol === "http:" &&
153 !isLocalLoopbackHost(parsed.hostname) &&
154 !isTailnetHost(parsed.hostname)
155 ) {
156 return Effect.fail(
157 new PeerLinkError({
158 reason: "unreachable",
159 message: `${url} is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`,
160 }),
161 );
162 }
163 return Effect.succeed(parsed.origin);
164};
165
166/** Whether a peer holds a linked agent to its limits and keeps its work within its link. */
167const linkLimitsHold = (peer: { readonly capabilities: ExecutionEnvironmentCapabilities }) =>
168 peer.capabilities.mcpModeLimitHeader === true && peer.capabilities.linkFence === true;
169
170const make = Effect.gen(function* () {
171 const sql = yield* SqlClient.SqlClient;
172 const secrets = yield* ServerSecretStore.ServerSecretStore;
173 const random = yield* SecureRandom.SecureRandom;
174 const digest = yield* Digest.Digest;
175 const httpClient = yield* HttpClient.HttpClient;
176 const environment = yield* ServerEnvironment.ServerEnvironment;
177 const serverSettings = yield* ServerSettings.ServerSettingsService;
178 const enabled = serverSettings.getSettings.pipe(
179 Effect.map((settings) => settings.linkedEnvironmentsEnabled),
180 Effect.orElseSucceed(() => false),
181 );
182
183 /** A fresh name for one link's token; the row records it. */
184 const newSecretName = random.randomBytes(16).pipe(
185 Effect.map((bytes) => `peer-link-${Hex.encode(bytes)}`),
186 Effect.orDie,
187 );
188
189 // Only the origin `peerOrigin` checked may receive a pairing code or token:
190 // a redirect could forward them anywhere, including plain http.
191 const peerHttpClient = HttpClient.transform(httpClient, (response) =>
192 Effect.provideService(response, FetchHttpClient.RequestInit, { redirect: "manual" }),
193 );
194
195 const clientFor = (origin: string) =>
196 HttpApiClient.make(PeerHttpApi, { baseUrl: origin }).pipe(
197 Effect.provideService(HttpClient.HttpClient, peerHttpClient),
198 );
199
200 /** The environment answering at `origin`, or nothing when it does not answer as T3 Code. */
201 const describe = (origin: string) =>
202 clientFor(origin).pipe(
203 Effect.flatMap((client) => client.metadata.descriptor()),
204 Effect.timeout(probeTimeout(origin)),
205 Effect.option,
206 );
207
208 const toLink = Effect.fn("PeerLinks.toLink")(function* (row: PeerLinkRow) {
209 return {
210 environmentId: EnvironmentId.make(row.environment_id),
211 label: row.label,
212 urls: yield* decodeUrls(row.urls_json),
213 access: yield* decodeAccess(row.access),
214 linkedAt: DateTime.makeUnsafe(row.linked_at),
215 // Its token predates link fencing, so the peer would not fence its work:
216 // like an expired link, only a new pairing code brings it back.
217 expiresAt: DateTime.makeUnsafe(row.fenced === 1 ? row.expires_at : row.linked_at),
218 lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at),
219 lastError: row.last_error,
220 } satisfies PeerLink;
221 }, Effect.catch(failStorage));
222
223 const readRows = sql<PeerLinkRow>`
224 SELECT * FROM peer_environment_links ORDER BY label, environment_id
225 `.pipe(NodeSqliteClient.readOnly, Effect.catch(failStorage));
226
227 const readRow = (environmentId: EnvironmentId) =>
228 sql<PeerLinkRow>`
229 SELECT * FROM peer_environment_links WHERE environment_id = ${environmentId}
230 `.pipe(
231 NodeSqliteClient.readOnly,
232 Effect.catch(failStorage),
233 Effect.map((rows) => Option.fromNullishOr(rows[0])),
234 );
235
236 /** Signs in to the peer's `/mcp` with a pairing code: register, decide, exchange. */
237 const signIn = Effect.fn("PeerLinks.signIn")(
238 function* (origin: string, input: PeerLinkCreateInput, clientName: string) {
239 const client = yield* clientFor(origin);
240 // Only the peer's own refusals are rejections. A dropped connection or
241 // an answer this version cannot read is classified below.
242 const registered = yield* client.mcpOAuth
243 .register({
244 payload: {
245 client_name: clientName,
246 redirect_uris: [LINK_REDIRECT_URI],
247 software_id: MCP_PEER_LINK_SOFTWARE_ID,
248 },
249 })
250 .pipe(
251 // A plain Schema.Error has no tag to catch by.
252 Effect.catchIf(Schema.is(AuthMcpRegistrationError), (error) =>
253 Effect.fail(
254 new PeerLinkError({
255 reason: "pairing_rejected",
256 message: `The peer refused to register this environment: ${error.message}`,
257 }),
258 ),
259 ),
260 );
261 const verifier = Base64Url.encode(yield* random.randomBytes(32));
262 const challenge = Base64Url.encode(
263 yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier)).pipe(Effect.orDie),
264 );
265 const state = Base64Url.encode(yield* random.randomBytes(16));
266 const resource = `${origin}/mcp`;
267 const decided = yield* client.mcpOAuth
268 .decision({
269 payload: {
270 authorization: {
271 response_type: "code",
272 client_id: registered.client_id,
273 redirect_uri: LINK_REDIRECT_URI,
274 code_challenge: challenge,
275 code_challenge_method: "S256",
276 state: Redacted.make(state),
277 resource,
278 },
279 decision: { _tag: "pairing-code", access: input.access, code: input.pairingCode },
280 },
281 })
282 .pipe(
283 Effect.catchTags({
284 AuthMcpApprovalError: (error) =>
285 Effect.fail(
286 new PeerLinkError({ reason: "pairing_rejected", message: error.message }),
287 ),
288 }),
289 );
290 const redirect = URL.parse(decided.redirectTo);
291 if (redirect === null) {
292 return yield* new PeerLinkError({
293 reason: "incompatible",
294 message: `${origin} answered the sign-in with an address this version cannot read. Update both environments.`,
295 });
296 }
297 const code = redirect.searchParams.get("code");
298 if (code === null || redirect.searchParams.get("state") !== state) {
299 return yield* new PeerLinkError({
300 reason: "pairing_rejected",
301 message:
302 redirect.searchParams.get("error_description") ??
303 "The peer did not approve the link. Check the pairing code and try again.",
304 });
305 }
306 return yield* client.mcpOAuth
307 .token({
308 payload: {
309 grant_type: "authorization_code",
310 code: Redacted.make(code),
311 redirect_uri: LINK_REDIRECT_URI,
312 client_id: registered.client_id,
313 code_verifier: Redacted.make(verifier),
314 resource,
315 },
316 })
317 .pipe(
318 Effect.catchIf(Schema.is(AuthMcpTokenError), (error) =>
319 Effect.fail(
320 new PeerLinkError({
321 reason: "pairing_rejected",
322 message: `The peer refused the sign-in: ${error.message}`,
323 }),
324 ),
325 ),
326 );
327 },
328 (effect, origin) =>
329 effect.pipe(
330 // Endpoint errors are mapped above; what is left is the transport or an
331 // answer this version cannot decode.
332 Effect.catchTags({
333 SchemaError: (cause) =>
334 Effect.fail(
335 new PeerLinkError({
336 reason: "incompatible",
337 message: `${origin} answered in a shape this version does not understand. Update both environments.`,
338 cause,
339 }),
340 ),
341 HttpClientError: (cause) =>
342 Effect.fail(
343 new PeerLinkError({
344 reason: "unreachable",
345 message: `${origin} stopped answering while linking.`,
346 cause,
347 }),
348 ),
349 }),
350 ),
351 );
352
353 /**
354 * The addresses that answer as `environmentId`, in the order given, with
355 * what the first one answered. Addresses this environment would not send
356 * credentials to are skipped; when every one is, the failure says why.
357 */
358 const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* (
359 urls: ReadonlyArray<string>,
360 environmentId: EnvironmentId,
361 name: string,
362 ) {
363 const checked = yield* Effect.forEach(
364 urls,
365 (url) =>
366 Effect.gen(function* () {
367 const origin = yield* peerOrigin(url);
368 return { origin, descriptor: yield* describe(origin) };
369 }).pipe(Effect.result),
370 { concurrency: "unbounded" },
371 );
372 const matching = checked.flatMap((result) =>
373 Result.isSuccess(result) &&
374 Option.isSome(result.success.descriptor) &&
375 result.success.descriptor.value.environmentId === environmentId
376 ? [{ origin: result.success.origin, descriptor: result.success.descriptor.value }]
377 : [],
378 );
379 const first = matching[0];
380 if (first === undefined) {
381 const refusals = checked.flatMap((result) =>
382 Result.isFailure(result) ? [result.failure.message] : [],
383 );
384 return yield* new PeerLinkError({
385 reason: "unreachable",
386 message:
387 refusals.length === checked.length
388 ? `This environment could not reach ${name}: ${refusals.join(" ")}`
389 : `This environment could not reach ${name} at ${urls.join(", ")}.`,
390 });
391 }
392 // Each address is kept once, even when two spellings share an origin.
393 const origins = [...new Set(matching.map((found) => found.origin))];
394 return { primary: first.origin, peer: first.descriptor, origins };
395 });
396
397 /** The peer at `url`, with every address checked for credentials first. */
398 const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray<string>) {
399 const origins = yield* Effect.forEach(urls, peerOrigin);
400 const primary = origins[0]!;
401 const descriptor = yield* describe(primary);
402 if (Option.isNone(descriptor)) {
403 return yield* new PeerLinkError({
404 reason: "not_a_t3_environment",
405 message: `Nothing at ${primary} answered as a T3 Code environment.`,
406 });
407 }
408 return { primary, peer: descriptor.value, origins };
409 });
410
411 const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {
412 if (!(yield* enabled)) {
413 return yield* new PeerLinkError({ reason: "disabled", message: LINKED_ENVIRONMENTS_OFF });
414 }
415 const urls = [input.url, ...(input.alternateUrls ?? [])];
416 // The user picked a machine: link through the addresses that prove to
417 // be it, so a reused LAN address never receives the pairing code.
418 const { primary, peer, origins } =
419 input.expectedEnvironmentId === undefined
420 ? yield* answeringAt(urls)
421 : yield* answeringAs(
422 urls,
423 input.expectedEnvironmentId,
424 input.expectedLabel ?? input.expectedEnvironmentId,
425 );
426 const self = yield* environment.getDescriptor;
427 if (peer.environmentId === self.environmentId) {
428 return yield* new PeerLinkError({
429 reason: "self",
430 message: "That address is this environment.",
431 });
432 }
433 if (!linkLimitsHold(peer)) {
434 return yield* new PeerLinkError({
435 reason: "incompatible",
436 message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
437 });
438 }
439 const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`);
440 const now = yield* DateTime.now;
441 const linked: PeerLink = {
442 environmentId: peer.environmentId,
443 label: peer.label,
444 urls: origins,
445 access: input.access,
446 linkedAt: now,
447 expiresAt: DateTime.add(now, { seconds: issued.expires_in }),
448 lastReachedAt: now,
449 lastError: null,
450 };
451 // The token goes under a name of its own before the row points at it,
452 // so the row and its token are replaced together.
453 const secretName = yield* newSecretName;
454 yield* secrets
455 .set(secretName, new TextEncoder().encode(issued.access_token))
456 .pipe(Effect.catch(failStorage));
457 // A token no row names could never be removed.
458 const previous = yield* Effect.gen(function* () {
459 const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
460 const previous = yield* readRow(peer.environmentId);
461 yield* sql`
462 INSERT INTO peer_environment_links (
463 environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
464 last_reached_at, last_error, fenced
465 ) VALUES (
466 ${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},
467 ${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},
468 ${DateTime.formatIso(now)}, NULL, 1
469 )
470 ON CONFLICT (environment_id) DO UPDATE SET
471 secret_name = excluded.secret_name,
472 fenced = excluded.fenced,
473 label = excluded.label,
474 urls_json = excluded.urls_json,
475 access = excluded.access,
476 linked_at = excluded.linked_at,
477 expires_at = excluded.expires_at,
478 last_reached_at = excluded.last_reached_at,
479 last_error = NULL
480 `.pipe(Effect.catch(failStorage));
481 return previous;
482 }).pipe(Effect.onError(() => secrets.remove(secretName).pipe(Effect.ignore)));
483 // Linking again replaces the old token. A racing link may leave its own
484 // behind; it is unused either way.
485 if (Option.isSome(previous) && previous.value.secret_name !== secretName) {
486 yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore);
487 }
488 return linked;
489 });
490
491 const describeUrl: PeerLinks["Service"]["describe"] = (url) =>
492 peerOrigin(url).pipe(
493 Effect.flatMap(describe),
494 Effect.map(Option.map((peer) => ({ environmentId: peer.environmentId, label: peer.label }))),
495 Effect.orElseSucceed(() => Option.none()),
496 );
497
498 /** A peer's label follows its machine name, so the link takes the one its own address answers with. */
499 const withLabel = (link: PeerLink, label: string) =>
500 label === link.label
501 ? Effect.succeed(link)
502 : sql`
503 UPDATE peer_environment_links SET label = ${label}
504 WHERE environment_id = ${link.environmentId}
505 `.pipe(Effect.ignoreCause({ log: true }), Effect.as({ ...link, label }));
506
507 const statusOf = Effect.fn("PeerLinks.statusOf")(function* (
508 link: PeerLink,
509 now: DateTime.Utc,
510 ): Effect.fn.Return<PeerLinkSummary> {
511 if (DateTime.isLessThanOrEqualTo(link.expiresAt, now)) return { ...link, status: "expired" };
512 let label = link.label;
513 const answered = yield* Effect.findFirst(link.urls, (url) =>
514 describe(url).pipe(
515 Effect.map((found) => {
516 if (Option.isNone(found) || found.value.environmentId !== link.environmentId) {
517 return false;
518 }
519 label = found.value.label;
520 return true;
521 }),
522 ),
523 );
524 if (Option.isNone(answered)) return { ...link, status: "unreachable" };
525 return { ...(yield* withLabel(link, label)), status: "reachable" };
526 });
527
528 const list: PeerLinks["Service"]["list"] = Effect.gen(function* () {
529 const links = yield* Effect.forEach(yield* readRows, toLink);
530 const now = yield* DateTime.now;
531 return yield* Effect.forEach(links, (link) => statusOf(link, now), {
532 concurrency: "unbounded",
533 });
534 });
535
536 const get: PeerLinks["Service"]["get"] = (environmentId) =>
537 readRow(environmentId).pipe(
538 Effect.flatMap(
539 Option.match({
540 onNone: () => Effect.succeedNone,
541 onSome: (row) => Effect.asSome(toLink(row)),
542 }),
543 ),
544 );
545
546 const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")(
547 function* (environmentId) {
548 const deleted = yield* sql<{ secret_name: string }>`
549 DELETE FROM peer_environment_links WHERE environment_id = ${environmentId}
550 RETURNING secret_name
551 `.pipe(Effect.catch(failStorage));
552 for (const row of deleted) {
553 yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage));
554 }
555 return deleted.length > 0;
556 },
557 );
558
559 const resolve: PeerLinks["Service"]["resolve"] = Effect.fn("PeerLinks.resolve")(
560 function* (environmentId) {
561 const row = yield* readRow(environmentId);
562 if (Option.isNone(row)) {
563 return yield* new PeerLinkError({
564 reason: "unknown_link",
565 message: `This environment is not linked to ${environmentId}. t3_environment_links lists the linked ones.`,
566 });
567 }
568 const link = yield* toLink(row.value);
569 if (DateTime.isLessThanOrEqualTo(link.expiresAt, yield* DateTime.now)) {
570 return yield* new PeerLinkError({
571 reason: "expired",
572 message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
573 });
574 }
575 const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
576 if (Option.isNone(stored)) {
577 return yield* new PeerLinkError({
578 reason: "unknown_link",
579 message: `The link to ${link.label} lost its credential. Link it again.`,
580 });
581 }
582 // The token goes only to an address that proves it is this peer, so a
583 // reused LAN address or a moved hostname never receives it.
584 let fenced = true;
585 let label = link.label;
586 const url = yield* Effect.findFirst(link.urls, (candidate) =>
587 describe(candidate).pipe(
588 Effect.map((found) => {
589 if (Option.isNone(found) || found.value.environmentId !== environmentId) return false;
590 fenced = linkLimitsHold(found.value);
591 label = found.value.label;
592 return true;
593 }),
594 ),
595 );
596 if (Option.isNone(url)) {
597 return yield* new PeerLinkError({
598 reason: "unreachable",
599 message: `${link.label} did not answer at ${link.urls.join(", ")}.`,
600 });
601 }
602 // A link made before the peer had to fence linked work, or a peer moved
603 // back to such a version, would carry work past those limits.
604 if (!fenced) {
605 return yield* new PeerLinkError({
606 reason: "incompatible",
607 message: `${link.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
608 });
609 }
610 return {
611 link: yield* withLabel(link, label),
612 url: url.value,
613 token: new TextDecoder().decode(stored.value),
614 };
615 },
616 );
617
618 const recordOutcome: PeerLinks["Service"]["recordOutcome"] = (environmentId, outcome) =>
619 DateTime.now.pipe(
620 Effect.flatMap((now) =>
621 outcome.error === null
622 ? sql`
623 UPDATE peer_environment_links
624 SET last_reached_at = ${DateTime.formatIso(now)}, last_error = NULL
625 WHERE environment_id = ${environmentId}
626 `
627 : sql`
628 UPDATE peer_environment_links SET last_error = ${outcome.error}
629 WHERE environment_id = ${environmentId}
630 `,
631 ),
632 Effect.asVoid,
633 Effect.ignoreCause({ log: true }),
634 );
635
636 return PeerLinks.of({
637 enabled,
638 link,
639 describe: describeUrl,
640 list,
641 get,
642 unlink,
643 resolve,
644 recordOutcome,
645 });
646});
647
648export const layer = Layer.effect(PeerLinks, make);