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

peerLinks.ts

217 lines8.5 KB

1import {
2 type EnvironmentId,
3 type PeerLinkSummary,
4 type PeerLinkThreadInput,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import * as DateTime from "effect/DateTime";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Stream from "effect/Stream";
11import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
12​
13import type { EnvironmentRegistry } from "../connection/registry.ts";
14import {
15 followLinkedThread,
16 keepLinkedThreadView,
17 type LinkedThreadView,
18} from "../linkedThread.ts";
19import { request, subscribe } from "../rpc/client.ts";
20import {
21 createEnvironmentRpcCommand,
22 createEnvironmentRpcQueryAtomFamily,
23 followStreamInEnvironment,
24} from "./runtime.ts";
25​
26/** The environment a client reads through, and the linked environment's thread it reads. */
27export interface LinkedThreadViewTarget {
28 readonly environmentId: EnvironmentId;
29 readonly input: PeerLinkThreadInput;
31​
32const threadViewKey = ({ environmentId, input }: LinkedThreadViewTarget) =>
33 JSON.stringify({
34 environmentId,
35 input: { environmentId: input.environmentId, threadId: input.threadId },
36 });
37​
38export function createPeerLinkEnvironmentAtoms<R, E>(
39 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
40) {
41 const list = createEnvironmentRpcQueryAtomFamily(runtime, {
42 label: "environment-data:peer-links:list",
43 tag: WS_METHODS.peerLinksList,
44 // Listing probes every linked environment, so a list stays fresh briefly.
45 staleTimeMs: 10_000,
46 });
47 // Names only, for opening linked threads with thread read access; it probes nothing.
48 const names = createEnvironmentRpcQueryAtomFamily(runtime, {
49 label: "environment-data:peer-links:names",
50 tag: WS_METHODS.peerLinksNames,
51 staleTimeMs: 10_000,
52 });
53 const refreshLinks = (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) =>
54 Effect.sync(() => {
55 registry.refresh(list({ environmentId, input: {} }));
56 registry.refresh(names({ environmentId, input: {} }));
57 });
58 /**
59 * What a view of the thread last showed. It outlives the subscription for a while, so coming
60 * back to the view shows the thread at once while the stream starts again.
61 */
62 const lastThreadView = Atom.family((key: string) =>
63 Atom.make<LinkedThreadView | null>(null).pipe(
64 Atom.setIdleTTL(5 * 60_000),
65 Atom.withLabel(`environment-data:peer-links:last-thread-view:${key}`),
66 ),
67 );
68 /**
69 * A linked environment's thread, streamed while a view reads it. The subscription ends with its
70 * last reader, which closes the stream at the linked environment too.
71 */
72 const threadView = Atom.family((key: string) => {
73 const { environmentId, input } = JSON.parse(key) as LinkedThreadViewTarget;
74 const kept = lastThreadView(key);
75 const stream = runtime
76 .atom(({ registry }) =>
77 followStreamInEnvironment(
78 environmentId,
79 Stream.suspend(() =>
80 followLinkedThread({
81 items: subscribe(WS_METHODS.peerLinksSubscribeThread, input),
82 historyPage: (cursor) =>
83 request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }),
84 previous: registry.get(kept),
85 }),
86 ),
87 ),
88 )
89 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`));
90 return Atom.make((get) => {
91 const live = get(stream);
92 if (AsyncResult.isSuccess(live)) {
93 get.set(kept, keepLinkedThreadView(get.once(kept), live.value));
94 }
95 return live;
96 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`));
97 });
98 return {
99 list,
100 names,
101 link: createEnvironmentRpcCommand(runtime, {
102 label: "environment-data:peer-links:link",
103 tag: WS_METHODS.peerLinksLink,
104 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
105 }),
106 // Leaves the list alone: a batch refreshes it once, when it ends (`runLinkBatch`).
107 linkInBatch: createEnvironmentRpcCommand(runtime, {
108 label: "environment-data:peer-links:link-in-batch",
109 tag: WS_METHODS.peerLinksLink,
110 }),
111 unlink: createEnvironmentRpcCommand(runtime, {
112 label: "environment-data:peer-links:unlink",
113 tag: WS_METHODS.peerLinksUnlink,
114 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
115 }),
116 threadView: (target: LinkedThreadViewTarget) => threadView(threadViewKey(target)),
117 lastThreadView: (target: LinkedThreadViewTarget) => lastThreadView(threadViewKey(target)),
118 /** One item of a linked environment's thread in full, for a row the reader opened. */
119 threadItem: createEnvironmentRpcQueryAtomFamily(runtime, {
120 label: "environment-data:peer-links:thread-item",
121 tag: WS_METHODS.peerLinksThreadItem,
122 idleTtlMs: 0,
123 }),
124 /** Asks for a one-time pairing with a linked environment. Its answer is a credential: never cached. */
125 pairClient: createEnvironmentRpcCommand(runtime, {
126 label: "environment-data:peer-links:pair-client",
127 tag: WS_METHODS.peerLinksPairClient,
128 concurrency: {
129 mode: "singleFlight",
130 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.environmentId]),
131 },
132 }),
133 /** Asks for a pairing code from a linked environment, to link another one there. Never cached. */
134 pairLink: createEnvironmentRpcCommand(runtime, {
135 label: "environment-data:peer-links:pair-link",
136 tag: WS_METHODS.peerLinksPairLink,
137 }),
138 // An agent's link card. One answer per card at a time.
139 answerRequest: createEnvironmentRpcCommand(runtime, {
140 label: "environment-data:peer-links:answer-request",
141 tag: WS_METHODS.peerLinksAnswerRequest,
142 concurrency: {
143 mode: "singleFlight",
144 key: ({ environmentId, input }) =>
145 JSON.stringify([environmentId, input.threadId, input.turnItemId]),
146 },
147 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
148 }),
149 };
151​
152const EXPIRY_WARNING_DAYS = 5;
153​
154export type PeerLinkHealth =
155 | { readonly kind: "reachable"; readonly expiresInDays: number | null }
156 | { readonly kind: "unreachable"; readonly detail: string | null }
157 | { readonly kind: "failing"; readonly detail: string }
158 | { readonly kind: "expired" };
159​
160/**
161 * Listing only checks that the peer answers, so a link whose last call failed
162 * (the peer revoked it, say) is `failing` with the recorded reason; the next
163 * successful call clears it.
164 */
165export function peerLinkHealth(link: PeerLinkSummary, now: DateTime.Utc): PeerLinkHealth {
166 if (link.status === "expired" || DateTime.isLessThanOrEqualTo(link.expiresAt, now)) {
167 return { kind: "expired" };
168 }
169 if (link.status === "unreachable") return { kind: "unreachable", detail: link.lastError };
170 if (link.lastError !== null) return { kind: "failing", detail: link.lastError };
171 const days = Math.ceil(Duration.toDays(DateTime.distance(now, link.expiresAt)));
172 return { kind: "reachable", expiresInDays: days <= EXPIRY_WARNING_DAYS ? days : null };
174​
175/** A linked machine, and the environment that can get a pairing code from it. */
176export interface LinkThroughRoute {
177 readonly viaEnvironmentId: EnvironmentId;
178 readonly environmentId: EnvironmentId;
179 readonly label: string;
180 readonly urls: ReadonlyArray<string>;
182​
183/**
184 * The machines `sourceEnvironmentId` can link to without a pasted code: those another of the
185 * client's environments reaches over a full-access link that answers. `hosts` are environments
186 * the client is connected to and manages access on, the only ones it may ask.
187 */
188export function linkThroughRoutes(input: {
189 readonly sourceEnvironmentId: EnvironmentId;
190 readonly hosts: ReadonlyArray<{
191 readonly environmentId: EnvironmentId;
192 readonly links: ReadonlyArray<PeerLinkSummary>;
193 }>;
194 readonly now: DateTime.Utc;
195}): ReadonlyMap<EnvironmentId, LinkThroughRoute> {
196 const routes = new Map<EnvironmentId, LinkThroughRoute>();
197 for (const host of input.hosts) {
198 if (host.environmentId === input.sourceEnvironmentId) continue;
199 for (const link of host.links) {
200 if (
201 link.environmentId === input.sourceEnvironmentId ||
202 link.access !== "full-access" ||
203 routes.has(link.environmentId) ||
204 peerLinkHealth(link, input.now).kind !== "reachable"
205 ) {
206 continue;
207 }
208 routes.set(link.environmentId, {
209 viaEnvironmentId: host.environmentId,
210 environmentId: link.environmentId,
211 label: link.label,
212 urls: link.urls,
213 });
214 }
215 }
216 return routes;