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

peerLinks.ts

197 lines7.8 KB

1import { 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 { 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 */
47export function useLinkedEnvironments(
48 environmentId: EnvironmentId | null,
49): ReadonlyMap<EnvironmentId, string> {
50 const offered = useAtomValue(
51 environmentId === null ? offersNoLinksAtom : offersLinkedEnvironmentsAtom(environmentId),
52 );
53 const identities = useEnvironmentIdentities();
54 const links = useEnvironmentQuery(
55 offered && environmentId !== null
56 ? peerLinkEnvironment.names({ environmentId, input: {} })
57 : null,
58 );
59 return linkedEnvironmentNames({
60 links: offered ? (links.data?.links ?? []) : [],
61 environments: identities,
62 });
64​
65export function usePeerLinkHosts() {
66 const { environments } = useEnvironments();
67 const supported = environments.filter(
68 (environment) =>
69 environment.connection.phase === "connected" &&
70 offersLinkedEnvironments(environment.serverConfig),
71 );
72 const readable = useEnvironmentsWithScope(supported, AuthAccessReadScope);
73 return supported.filter((environment) => readable.has(environment.environmentId));
75​
76/**
77 * The user's other machines, for picking one to link `environmentId` to,
78 * including those only on their T3 Connect account. Reads that environment's
79 * links only while `enabled`, since listing them asks every linked machine
80 * whether it answers.
81 */
82export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
83 const { environments } = useEnvironments();
84 const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
85 const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
86 reportFailure: false,
87 });
88 // Connect hosts are listed only once something asked for them, so ask on open.
89 const discoverIfUnasked = useEffectEvent(() => {
90 if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery();
91 });
92 // 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
93 useEffect(() => {
94 if (enabled) discoverIfUnasked();
95 }, [enabled]);
96 const links = useEnvironmentQuery(
97 enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
98 );
99 return linkableMachines({
100 environments,
101 threadEnvironmentId: environmentId,
102 links: links.data?.links ?? [],
103 connect: discovery.environments,
104 });
106​
107/**
108 * The machines `sourceId` can link to through another environment's full-access link, by
109 * environment id. Reads those environments' links only while `enabled`: listing them asks every
110 * linked machine whether it answers.
111 */
112export function useLinkThroughRoutes(sourceId: EnvironmentId, enabled: boolean) {
113 const { environments } = useEnvironments();
114 const writable = useEnvironmentsWithScope(environments, AuthAccessWriteScope);
115 const nowMinute = useNowMinute();
116 const hosts = environments
117 .filter(
118 (environment) =>
119 enabled &&
120 environment.environmentId !== sourceId &&
121 environment.connection.phase === "connected" &&
122 offersLinkedEnvironments(environment.serverConfig) &&
123 writable.has(environment.environmentId),
124 )
125 .map((environment) => environment.environmentId);
126 const lists = useAtomValue(peerLinkListsAtom(environmentIdsKey(hosts)));
127 return linkThroughRoutes({
128 sourceEnvironmentId: sourceId,
129 hosts: hosts.map((environmentId, index) => {
130 const list = lists[index];
131 return { environmentId, links: list?._tag === "Success" ? list.value.links : [] };
132 }),
133 now: DateTime.makeUnsafe(nowMinute),
134 });
136​
137const NOT_OFFERED: LinkBackOffer = { kind: "hidden" };
138​
139/**
140 * Whether linking `sourceId` to each of `targetIds` can also link that machine back, and the
141 * source as the reverse link names it. Only machines that could link back are asked for their
142 * links, and only while `enabled`: listing asks every machine they link to whether it answers.
143 */
144export function useLinkBackOffers(
145 sourceId: EnvironmentId,
146 targetIds: ReadonlyArray<EnvironmentId>,
147 enabled: boolean,
148) {
149 const { environments } = useEnvironments();
150 const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
151 const writable = useEnvironmentsWithScope(environments, AuthAccessWriteScope);
152 const source = linkableMachines({
153 environments,
154 threadEnvironmentId: null,
155 links: [],
156 connect: discovery.environments,
157 }).find((machine) => machine.environmentId === sourceId);
158 const wanted = new Set(targetIds);
159 const targets = environments.filter((environment) => wanted.has(environment.environmentId));
160 const listed = targets
161 .filter(
162 (target) =>
163 enabled &&
164 target.connection.phase === "connected" &&
165 offersLinkedEnvironments(target.serverConfig) &&
166 writable.has(target.environmentId),
167 )
168 .map((target) => target.environmentId);
169 const lists = useAtomValue(peerLinkListsAtom(environmentIdsKey(listed)));
170 const offers = new Map<EnvironmentId, LinkBackOffer>();
171 for (const target of targets) {
172 if (source === undefined) break;
173 const list = lists[listed.indexOf(target.environmentId)];
174 offers.set(
175 target.environmentId,
176 linkBackOffer({
177 source: {
178 environmentId: sourceId,
179 connected: source.connected,
180 writable: writable.has(sourceId),
181 urls: source.urls,
182 },
183 target: {
184 connected: target.connection.phase === "connected",
185 offersLinks: offersLinkedEnvironments(target.serverConfig),
186 writable: writable.has(target.environmentId),
187 links: list?._tag === "Success" ? list.value.links : null,
188 },
189 }),
190 );
191 }
192 return {
193 source: source ?? null,
194 offerFor: (targetId: EnvironmentId | null): LinkBackOffer =>
195 (targetId === null ? undefined : offers.get(targetId)) ?? NOT_OFFERED,
196 };