Open History to see the last commit
1import { RegistryContext, useAtomValue } from "@effect/atom-react";
2import {
3 linkableMachines,
4 linkedEnvironmentNames,
5 offersLinkedEnvironments,
6} from "@t3tools/client-runtime/link-request";
7import { linkBackOffer, type LinkBackOffer } from "@t3tools/client-runtime/link-batch";
8import {
9 createPeerLinkEnvironmentAtoms,
10 linkThroughRoutes,
11} from "@t3tools/client-runtime/state/peerLinks";
12import { AuthAccessReadScope, AuthAccessWriteScope, type EnvironmentId } from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import { Atom } from "effect/reactivity";
15import { useContext, useEffect, useEffectEvent } from "react";
16
17import { useNowMinute } from "../hooks/useNowMinute";
18import { connectionAtomRuntime } from "../connection/runtime";
19import { environmentAtomList, environmentIdsKey } from "./environmentAtomList";
20import { useEnvironmentIdentities, useEnvironments } from "./environments";
21import { environmentPresentations } from "./presentation";
22import { relayEnvironmentDiscovery } from "./relay";
23import { useEnvironmentQuery } from "./query";
24import { useEnvironmentsWithScope } from "./session";
25import { useAtomCommand } from "./use-atom-command";
26
27export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
28
29/** Each environment's link list as the settings list loads it, in the order of the ids. */
30export const peerLinkListsAtom = environmentAtomList("peer-links:lists", (environmentId) =>
31 peerLinkEnvironment.list({ environmentId, input: {} }),
32);
33
34/** Whether `environmentId` offers links, so its threads may name another machine. */
35export const offersLinkedEnvironmentsAtom = Atom.family((environmentId: EnvironmentId) =>
36 Atom.make((get) =>
37 offersLinkedEnvironments(get(environmentPresentations.serverConfigsAtom).get(environmentId)),
38 ).pipe(Atom.withLabel(`peer-links:offered:${environmentId}`)),
39);
40
41const offersNoLinksAtom = Atom.make(false).pipe(Atom.withLabel("peer-links:offered:none"));
42
43/**
44 * The machines `environmentId` links to, by name, while it offers links, and none otherwise.
45 * Its agents can read threads there, and so can a client allowed to read threads on it.
46 * A `wanted` machine the names lack makes them reread.
47 */
48export function useLinkedEnvironments(
49 environmentId: EnvironmentId | null,
50 wanted?: EnvironmentId,
51): ReadonlyMap<EnvironmentId, string> {
52 const offered = useAtomValue(
53 environmentId === null ? offersNoLinksAtom : offersLinkedEnvironmentsAtom(environmentId),
54 );
55 const identities = useEnvironmentIdentities();
56 const links = useEnvironmentQuery(
57 offered && environmentId !== null
58 ? peerLinkEnvironment.names({ environmentId, input: {} })
59 : null,
60 );
61 const registry = useContext(RegistryContext);
62 const queried = offered ? environmentId : null;
63 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links made outside this client are not pushed, so meeting an unknown machine asks the server again
64 useEffect(() => {
65 if (queried === null || wanted === undefined) return;
66 peerLinkEnvironment.refreshNamesLacking(registry, queried, [wanted]);
67 }, [registry, queried, wanted]);
68 return linkedEnvironmentNames({
69 links: offered ? (links.data?.links ?? []) : [],
70 environments: identities,
71 });
72}
73
74export function usePeerLinkHosts() {
75 const { environments } = useEnvironments();
76 const supported = environments.filter(
77 (environment) =>
78 environment.connection.phase === "connected" &&
79 offersLinkedEnvironments(environment.serverConfig),
80 );
81 const readable = useEnvironmentsWithScope(supported, AuthAccessReadScope);
82 return supported.filter((environment) => readable.has(environment.environmentId));
83}
84
85/**
86 * The user's other machines, for picking one to link `environmentId` to,
87 * including those only on their T3 Connect account. Reads that environment's
88 * links only while `enabled`, since listing them asks every linked machine
89 * whether it answers.
90 */
91export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
92 const { environments } = useEnvironments();
93 const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
94 const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
95 reportFailure: false,
96 });
97 // Connect hosts are listed only once something asked for them, so ask on open.
98 const discoverIfUnasked = useEffectEvent(() => {
99 if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery();
100 });
101 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- discovery follows the picker's visibility, which a card's mount or a dialog's open sets
102 useEffect(() => {
103 if (enabled) discoverIfUnasked();
104 }, [enabled]);
105 const links = useEnvironmentQuery(
106 enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
107 );
108 return linkableMachines({
109 environments,
110 threadEnvironmentId: environmentId,
111 links: links.data?.links ?? [],
112 connect: discovery.environments,
113 });
114}
115
116/**
117 * The machines `sourceId` can link to through another environment's full-access link, by
118 * environment id. Reads those environments' links only while `enabled`: listing them asks every
119 * linked machine whether it answers.
120 */
121export function useLinkThroughRoutes(sourceId: EnvironmentId, enabled: boolean) {
122 const { environments } = useEnvironments();
123 const writable = useEnvironmentsWithScope(environments, AuthAccessWriteScope);
124 const nowMinute = useNowMinute();
125 const hosts = environments
126 .filter(
127 (environment) =>
128 enabled &&
129 environment.environmentId !== sourceId &&
130 environment.connection.phase === "connected" &&
131 offersLinkedEnvironments(environment.serverConfig) &&
132 writable.has(environment.environmentId),
133 )
134 .map((environment) => environment.environmentId);
135 const lists = useAtomValue(peerLinkListsAtom(environmentIdsKey(hosts)));
136 return linkThroughRoutes({
137 sourceEnvironmentId: sourceId,
138 hosts: hosts.map((environmentId, index) => {
139 const list = lists[index];
140 return { environmentId, links: list?._tag === "Success" ? list.value.links : [] };
141 }),
142 now: DateTime.makeUnsafe(nowMinute),
143 });
144}
145
146const NOT_OFFERED: LinkBackOffer = { kind: "hidden" };
147
148/**
149 * Whether linking `sourceId` to each of `targetIds` can also link that machine back, and the
150 * source as the reverse link names it. Only machines that could link back are asked for their
151 * links, and only while `enabled`: listing asks every machine they link to whether it answers.
152 */
153export function useLinkBackOffers(
154 sourceId: EnvironmentId,
155 targetIds: ReadonlyArray<EnvironmentId>,
156 enabled: boolean,
157) {
158 const { environments } = useEnvironments();
159 const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
160 const writable = useEnvironmentsWithScope(environments, AuthAccessWriteScope);
161 const source = linkableMachines({
162 environments,
163 threadEnvironmentId: null,
164 links: [],
165 connect: discovery.environments,
166 }).find((machine) => machine.environmentId === sourceId);
167 const wanted = new Set(targetIds);
168 const targets = environments.filter((environment) => wanted.has(environment.environmentId));
169 const listed = targets
170 .filter(
171 (target) =>
172 enabled &&
173 target.connection.phase === "connected" &&
174 offersLinkedEnvironments(target.serverConfig) &&
175 writable.has(target.environmentId),
176 )
177 .map((target) => target.environmentId);
178 const lists = useAtomValue(peerLinkListsAtom(environmentIdsKey(listed)));
179 const offers = new Map<EnvironmentId, LinkBackOffer>();
180 for (const target of targets) {
181 if (source === undefined) break;
182 const list = lists[listed.indexOf(target.environmentId)];
183 offers.set(
184 target.environmentId,
185 linkBackOffer({
186 source: {
187 environmentId: sourceId,
188 connected: source.connected,
189 writable: writable.has(sourceId),
190 urls: source.urls,
191 },
192 target: {
193 connected: target.connection.phase === "connected",
194 offersLinks: offersLinkedEnvironments(target.serverConfig),
195 writable: writable.has(target.environmentId),
196 links: list?._tag === "Success" ? list.value.links : null,
197 },
198 }),
199 );
200 }
201 return {
202 source: source ?? null,
203 offerFor: (targetId: EnvironmentId | null): LinkBackOffer =>
204 (targetId === null ? undefined : offers.get(targetId)) ?? NOT_OFFERED,
205 };
206}