feat(clients): reach one environment over several routes (#15467)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
fe417dff4c
commit
979ca66ced
48 files changed
+2963
-434
No files matched your search
@@ -13,10 +13,20 @@ const onboardingScheduler = createAtomCommandScheduler();
|
||||
export const connectPairingUrl = createRuntimeCommand(connectionAtomRuntime, {
|
||||
label: "mobile:connection:connect-pairing-url",
|
||||
scheduler: onboardingScheduler,
|
||||
concurrency: { mode: "singleFlight", key: (pairingUrl: string) => pairingUrl },
|
||||
execute: (pairingUrl: string) =>
|
||||
concurrency: {
|
||||
mode: "singleFlight",
|
||||
// Adding a route to a different machine with the same link is its own
|
||||
// operation: it must check its own expected machine.
|
||||
key: (input: { readonly pairingUrl: string; readonly expectedEnvironmentId?: EnvironmentId }) =>
|
||||
JSON.stringify([input.pairingUrl, input.expectedEnvironmentId ?? null]),
|
||||
},
|
||||
execute: (input: {
|
||||
readonly pairingUrl: string;
|
||||
/** Set when adding a route to this saved machine. */
|
||||
readonly expectedEnvironmentId?: EnvironmentId;
|
||||
}) =>
|
||||
ConnectionOnboarding.ConnectionOnboarding.pipe(
|
||||
Effect.flatMap((onboarding) => onboarding.registerPairing({ pairingUrl })),
|
||||
Effect.flatMap((onboarding) => onboarding.registerPairing(input)),
|
||||
),
|
||||
});
|
||||
|
||||
|
||||
@@ -82,29 +82,75 @@ const connectivityLayer = Connectivity.layer({
|
||||
),
|
||||
});
|
||||
|
||||
/**
|
||||
* Wakes connections when the device moves between networks while staying
|
||||
* online, such as Wi-Fi to cellular. Connectivity only reports online or
|
||||
* offline, so leaving home on cellular would otherwise go unnoticed until the
|
||||
* LAN socket times out.
|
||||
*/
|
||||
const networkPathChanges = Stream.callback<"network-changed">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
let active = true;
|
||||
let previous: Network.NetworkStateType | undefined;
|
||||
const record = (state: Network.NetworkState) => {
|
||||
const type = state.isConnected === true ? state.type : undefined;
|
||||
if (previous !== undefined && type !== undefined && type !== previous) {
|
||||
Queue.offerUnsafe(queue, "network-changed");
|
||||
}
|
||||
previous = type ?? previous;
|
||||
};
|
||||
// The listener reports changes only, so seed the current type; without
|
||||
// it the first Wi-Fi to cellular move would go unnoticed.
|
||||
void Network.getNetworkStateAsync()
|
||||
.then((state) => {
|
||||
if (active && previous === undefined && state.isConnected === true) {
|
||||
previous = state.type;
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
const subscription = Network.addNetworkStateListener(record);
|
||||
return {
|
||||
remove: () => {
|
||||
active = false;
|
||||
subscription.remove();
|
||||
},
|
||||
};
|
||||
}),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
);
|
||||
|
||||
const wakeupsLayer = Wakeups.layer({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
|
||||
return AppState.addEventListener("change", (state) => {
|
||||
if (state === "background") {
|
||||
backgroundedAtMs = Date.now();
|
||||
return;
|
||||
}
|
||||
if (state === "active") {
|
||||
Queue.offerUnsafe(queue, mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()));
|
||||
backgroundedAtMs = null;
|
||||
}
|
||||
});
|
||||
}),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
),
|
||||
changes: Stream.mergeAll(
|
||||
[
|
||||
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
|
||||
return AppState.addEventListener("change", (state) => {
|
||||
if (state === "background") {
|
||||
backgroundedAtMs = Date.now();
|
||||
return;
|
||||
}
|
||||
if (state === "active") {
|
||||
Queue.offerUnsafe(
|
||||
queue,
|
||||
mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()),
|
||||
);
|
||||
backgroundedAtMs = null;
|
||||
}
|
||||
});
|
||||
}),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
),
|
||||
networkPathChanges,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
registerConnectionInCatalog,
|
||||
removeConnectionFromCatalog,
|
||||
setConnectionEnabledInCatalog,
|
||||
setRoutesInCatalog,
|
||||
removeCatalogValue,
|
||||
replaceCatalogValue,
|
||||
Persistence,
|
||||
@@ -27,6 +28,7 @@ function targetPersistenceError(
|
||||
| "list-targets"
|
||||
| "list-disabled-targets"
|
||||
| "register-connection"
|
||||
| "set-connection-routes"
|
||||
| "remove-connection"
|
||||
| "set-connection-enabled",
|
||||
error: ConnectionTransientError,
|
||||
@@ -57,13 +59,17 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
});
|
||||
const registrationStore = Persistence.ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
register: (registration, routes) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.update((document) => registerConnectionInCatalog(document, registration, routes))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
|
||||
remove: (target) =>
|
||||
setRoutes: (environmentId, routes) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.update((document) => setRoutesInCatalog(document, environmentId, routes))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("set-connection-routes", error))),
|
||||
remove: (environmentId) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, environmentId))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
setEnabled: (environmentId, enabled) =>
|
||||
catalog
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentRegistry, connectionRoutes } from "@t3tools/client-runtime/connection";
|
||||
import { createRuntimeCommand } from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -27,7 +27,10 @@ export const removeCloudEnvironments = createRuntimeCommand(connectionAtomRuntim
|
||||
const entries = yield* SubscriptionRef.get(registry.entries);
|
||||
const environmentIds = new Set(
|
||||
[...entries.values()]
|
||||
.filter((entry) => entry.target._tag === "RelayConnectionTarget")
|
||||
// Only environments that sign-out removes entirely lose their drafts.
|
||||
.filter((entry) =>
|
||||
connectionRoutes(entry).every((route) => route.target._tag === "RelayConnectionTarget"),
|
||||
)
|
||||
.map((entry) => entry.target.environmentId),
|
||||
);
|
||||
// Credentials are already revoked. A failed backup must leave the local
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
useRoute,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Linking, Platform, View } from "react-native";
|
||||
@@ -23,6 +24,8 @@ type ConnectionsNewRouteParams = {
|
||||
readonly mode?: string;
|
||||
readonly pairingUrl?: string;
|
||||
readonly autoConnect?: string;
|
||||
/** Adds a route to this saved machine instead of a new environment. */
|
||||
readonly routeFor?: EnvironmentId;
|
||||
};
|
||||
|
||||
export function ConnectionsNewRouteScreen({
|
||||
@@ -158,7 +161,7 @@ export function ConnectionsNewRouteScreen({
|
||||
setIsSubmitting(true);
|
||||
onChangeConnectionPairingUrl(pairingUrl);
|
||||
try {
|
||||
const result = await onConnectPress(pairingUrl);
|
||||
const result = await onConnectPress(pairingUrl, params.routeFor);
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
if (replaceWithHome || !navigation.canGoBack()) {
|
||||
navigation.dispatch(StackActions.replace("Home"));
|
||||
@@ -170,7 +173,7 @@ export function ConnectionsNewRouteScreen({
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
},
|
||||
[navigation, onChangeConnectionPairingUrl, onConnectPress],
|
||||
[navigation, onChangeConnectionPairingUrl, onConnectPress, params.routeFor],
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
|
||||
@@ -157,4 +157,21 @@ describe("mobile environment settings sections", () => {
|
||||
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
|
||||
expect(sections.availableCloudEnvironments).toEqual([]);
|
||||
});
|
||||
|
||||
it("offers T3 Connect for a machine saved only over the LAN, as an added route", () => {
|
||||
const local = connectedEnvironment({
|
||||
environmentId: "environment-desk",
|
||||
isRelayManaged: false,
|
||||
});
|
||||
|
||||
const sections = splitEnvironmentSections({
|
||||
connectedEnvironments: [local],
|
||||
cloudEnvironments: [cloudEnvironment("environment-desk")],
|
||||
});
|
||||
|
||||
expect(sections.localEnvironments).toEqual([local]);
|
||||
expect(
|
||||
sections.availableCloudEnvironments.map((environment) => environment.environmentId),
|
||||
).toEqual([EnvironmentId.make("environment-desk")]);
|
||||
});
|
||||
});
|
||||
@@ -69,7 +69,11 @@ export function useConnectionController() {
|
||||
);
|
||||
|
||||
const connectPairingUrl = useCallback(
|
||||
(pairingUrl: string) => connectPairingUrlMutation(pairingUrl),
|
||||
(pairingUrl: string, expectedEnvironmentId?: EnvironmentId) =>
|
||||
connectPairingUrlMutation({
|
||||
pairingUrl,
|
||||
...(expectedEnvironmentId === undefined ? {} : { expectedEnvironmentId }),
|
||||
}),
|
||||
[connectPairingUrlMutation],
|
||||
);
|
||||
const connectRelayEnvironment = useCallback(
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
type ConnectionRoute,
|
||||
connectionRouteAddress,
|
||||
connectionRouteId,
|
||||
connectionRouteLabel,
|
||||
connectionRoutes,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, Pressable, View } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { environmentCatalog } from "../../connection/catalog";
|
||||
import { environmentSession } from "../../state/session";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
|
||||
const ROW_HEIGHT = 64;
|
||||
|
||||
/**
|
||||
* The ways this device reaches an environment, preferred first. The first
|
||||
* route that answers is used, and the connection moves back up the list when
|
||||
* a better route is reachable again. Edit shows drag handles and remove
|
||||
* buttons; Add route pairs this machine over another address.
|
||||
*/
|
||||
export function EnvironmentRoutesSection({
|
||||
environmentId,
|
||||
connected,
|
||||
onAddRoute,
|
||||
}: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly connected: boolean;
|
||||
readonly onAddRoute: () => void;
|
||||
}) {
|
||||
const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);
|
||||
const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));
|
||||
const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder");
|
||||
const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal");
|
||||
const [editing, setEditing] = useState(false);
|
||||
const saved = entry === undefined ? [] : connectionRoutes(entry);
|
||||
const savedIds = saved.map((route) => connectionRouteId(route.target));
|
||||
// A dropped order shows until the catalog matches it.
|
||||
const [pending, setPending] = useState<ReadonlyArray<string> | null>(null);
|
||||
const order =
|
||||
pending !== null &&
|
||||
pending.length === savedIds.length &&
|
||||
pending.some((id, index) => id !== savedIds[index])
|
||||
? pending
|
||||
: savedIds;
|
||||
const [drag, setDrag] = useState<{ readonly id: string; readonly translation: number } | null>(
|
||||
null,
|
||||
);
|
||||
if (entry === undefined) return null;
|
||||
|
||||
const byId = new Map(saved.map((route) => [connectionRouteId(route.target), route]));
|
||||
const routes = order.flatMap((id) => byId.get(id) ?? []);
|
||||
const activeRouteId =
|
||||
connected && Option.isSome(prepared) ? connectionRouteId(prepared.value.target) : null;
|
||||
|
||||
const commit = (next: ReadonlyArray<string>) => {
|
||||
setPending(next);
|
||||
void reorder({ environmentId, routeIds: next }).then((result) => {
|
||||
if (result._tag === "Failure") setPending(null);
|
||||
});
|
||||
};
|
||||
const move = (from: number, to: number) => {
|
||||
if (to < 0 || to >= order.length || from === to) return;
|
||||
const next = [...order];
|
||||
const [moved] = next.splice(from, 1);
|
||||
next.splice(to, 0, moved!);
|
||||
commit(next);
|
||||
};
|
||||
const dropIndex = (from: number, translation: number) =>
|
||||
Math.max(0, Math.min(order.length - 1, from + Math.round(translation / ROW_HEIGHT)));
|
||||
const confirmRemove = (route: ConnectionRoute) =>
|
||||
Alert.alert(
|
||||
`Remove ${connectionRouteLabel(route)}?`,
|
||||
connectionRouteAddress(route) ?? undefined,
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Remove",
|
||||
style: "destructive",
|
||||
onPress: () =>
|
||||
void removeRoute({ environmentId, routeId: connectionRouteId(route.target) }),
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
const dragFrom = drag === null ? -1 : order.indexOf(drag.id);
|
||||
const dragTo = drag === null ? -1 : dropIndex(dragFrom, drag.translation);
|
||||
|
||||
return (
|
||||
<SettingsSection
|
||||
title="Routes"
|
||||
trailing={
|
||||
routes.length > 1 ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => setEditing((value) => !value)}
|
||||
className="px-2 py-1 active:opacity-70"
|
||||
>
|
||||
<Text className="text-sm font-t3-medium text-primary-text">
|
||||
{editing ? "Done" : "Edit"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{routes.map((route, index) => {
|
||||
const id = connectionRouteId(route.target);
|
||||
// Rows between the lifted row and its drop slot shift to make room.
|
||||
const shift =
|
||||
dragFrom === -1 || index === dragFrom
|
||||
? 0
|
||||
: dragFrom < dragTo && index > dragFrom && index <= dragTo
|
||||
? -ROW_HEIGHT
|
||||
: dragFrom > dragTo && index < dragFrom && index >= dragTo
|
||||
? ROW_HEIGHT
|
||||
: 0;
|
||||
return (
|
||||
<RouteRow
|
||||
key={id}
|
||||
route={route}
|
||||
position={index + 1}
|
||||
count={routes.length}
|
||||
inUse={id === activeRouteId}
|
||||
editing={editing}
|
||||
offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
|
||||
lifted={index === dragFrom}
|
||||
onDragStart={() => setDrag({ id, translation: 0 })}
|
||||
onDragMove={(translation) => setDrag({ id, translation })}
|
||||
onDragEnd={(translation, cancelled) => {
|
||||
setDrag(null);
|
||||
if (!cancelled) move(index, dropIndex(index, translation));
|
||||
}}
|
||||
onStep={(direction) => move(index, direction === "up" ? index - 1 : index + 1)}
|
||||
// The last route goes with the machine, which is "Remove" on the row.
|
||||
onRemove={routes.length > 1 ? () => confirmRemove(route) : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={onAddRoute}
|
||||
className="flex-row items-center gap-3 px-4 py-3.5 active:opacity-70"
|
||||
>
|
||||
<SymbolView name="plus" size={16} tintColorClassName="accent-icon" type="monochrome" />
|
||||
<Text className="text-base text-primary-text">Add route</Text>
|
||||
</Pressable>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function RouteRow(props: {
|
||||
readonly route: ConnectionRoute;
|
||||
readonly position: number;
|
||||
readonly count: number;
|
||||
readonly inUse: boolean;
|
||||
readonly editing: boolean;
|
||||
readonly offset: number;
|
||||
readonly lifted: boolean;
|
||||
readonly onDragStart: () => void;
|
||||
readonly onDragMove: (translation: number) => void;
|
||||
readonly onDragEnd: (translation: number, cancelled: boolean) => void;
|
||||
readonly onStep: (direction: "up" | "down") => void;
|
||||
readonly onRemove: (() => void) | undefined;
|
||||
}) {
|
||||
const { route, lifted, offset } = props;
|
||||
const label = connectionRouteLabel(route);
|
||||
const address = connectionRouteAddress(route);
|
||||
const style = useAnimatedStyle(() => ({
|
||||
transform: [
|
||||
{
|
||||
translateY: lifted
|
||||
? offset
|
||||
: withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }),
|
||||
},
|
||||
],
|
||||
zIndex: lifted ? 1 : 0,
|
||||
}));
|
||||
return (
|
||||
<Reanimated.View
|
||||
style={[{ height: ROW_HEIGHT }, style]}
|
||||
className={
|
||||
lifted ? "flex-row items-center bg-grouped-card shadow-md" : "flex-row items-center"
|
||||
}
|
||||
>
|
||||
{props.editing && props.onRemove ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Remove ${label} route`}
|
||||
onPress={props.onRemove}
|
||||
className="h-full items-center justify-center pl-4 active:opacity-70"
|
||||
>
|
||||
<SymbolView
|
||||
name="xmark.circle.fill"
|
||||
size={20}
|
||||
tintColorClassName="accent-danger-foreground"
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<View
|
||||
accessible
|
||||
accessibilityLabel={[
|
||||
label,
|
||||
address,
|
||||
props.inUse ? "In use" : null,
|
||||
`Route ${props.position} of ${props.count}`,
|
||||
]
|
||||
.filter((part) => part !== null)
|
||||
.join(", ")}
|
||||
className="min-w-0 flex-1 gap-0.5 px-4"
|
||||
>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text className="text-base text-foreground">{label}</Text>
|
||||
{props.inUse ? (
|
||||
<Text className="text-xs font-t3-medium text-success-foreground">In use</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{address !== null ? (
|
||||
<Text numberOfLines={1} className="text-sm text-foreground-muted">
|
||||
{address}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{props.editing ? (
|
||||
<DragHandle
|
||||
title={label}
|
||||
canMoveUp={props.position > 1}
|
||||
canMoveDown={props.position < props.count}
|
||||
onStart={props.onDragStart}
|
||||
onMove={props.onDragMove}
|
||||
onEnd={props.onDragEnd}
|
||||
onStep={props.onStep}
|
||||
/>
|
||||
) : null}
|
||||
</Reanimated.View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Pan recognition wins over the settings scroll view only inside the handle. */
|
||||
function DragHandle(props: {
|
||||
readonly title: string;
|
||||
readonly canMoveUp: boolean;
|
||||
readonly canMoveDown: boolean;
|
||||
readonly onStart: () => void;
|
||||
readonly onMove: (translation: number) => void;
|
||||
readonly onEnd: (translation: number, cancelled: boolean) => void;
|
||||
readonly onStep: (direction: "up" | "down") => void;
|
||||
}) {
|
||||
const latest = useRef(props);
|
||||
useEffect(() => {
|
||||
latest.current = props;
|
||||
});
|
||||
const translation = useRef(0);
|
||||
const gesture = useMemo(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.minDistance(0)
|
||||
.shouldCancelWhenOutside(false)
|
||||
.runOnJS(true)
|
||||
.onStart(() => {
|
||||
translation.current = 0;
|
||||
latest.current.onStart();
|
||||
})
|
||||
.onUpdate((event) => {
|
||||
translation.current = event.translationY;
|
||||
latest.current.onMove(event.translationY);
|
||||
})
|
||||
.onFinalize((_, success) => latest.current.onEnd(translation.current, !success)),
|
||||
[],
|
||||
);
|
||||
return (
|
||||
<GestureDetector gesture={gesture}>
|
||||
<View
|
||||
collapsable={false}
|
||||
accessible
|
||||
accessibilityRole="adjustable"
|
||||
accessibilityLabel={`Reorder ${props.title}`}
|
||||
accessibilityActions={[
|
||||
...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
|
||||
...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
|
||||
]}
|
||||
onAccessibilityAction={({ nativeEvent }) => {
|
||||
if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
|
||||
if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
|
||||
}}
|
||||
style={{ width: 48, height: ROW_HEIGHT, alignItems: "center", justifyContent: "center" }}
|
||||
>
|
||||
<SymbolView
|
||||
name="line.3.horizontal"
|
||||
size={20}
|
||||
tintColorClassName="accent-foreground-muted"
|
||||
/>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { StaticScreenProps } from "@react-navigation/native";
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
@@ -15,6 +15,7 @@ import { environmentSession } from "../../state/session";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
|
||||
import { EnvironmentRoutesSection } from "./EnvironmentRoutesSection";
|
||||
import { SettingsActionRow } from "./components/SettingsActionRow";
|
||||
import { SettingsScreen } from "./components/SettingsScreen";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
@@ -41,6 +42,7 @@ export function SettingsEnvironmentDetailRouteScreen({
|
||||
|
||||
function EnvironmentDetail({ environmentId }: { readonly environmentId: EnvironmentId }) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const navigation = useNavigation();
|
||||
const connections = useRemoteConnections();
|
||||
const environment = connections.connectedEnvironments.find(
|
||||
(entry) => entry.environmentId === environmentId,
|
||||
@@ -167,6 +169,19 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
|
||||
onUpdate={connections.onUpdateEnvironment}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<EnvironmentRoutesSection
|
||||
environmentId={environmentId}
|
||||
connected={connected}
|
||||
onAddRoute={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: {
|
||||
screen: "SettingsEnvironmentNew",
|
||||
params: { routeFor: environmentId },
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
{!connected ? (
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
Connect this environment to manage it.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
connectionCatalogDisplayUrl,
|
||||
hasRelayRoute,
|
||||
type EnvironmentPresentation as BaseEnvironmentPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
@@ -26,7 +27,7 @@ export function projectEnvironmentPresentation(
|
||||
environmentId,
|
||||
label: presentation.entry.target.label,
|
||||
displayUrl: connectionCatalogDisplayUrl(presentation.entry),
|
||||
relayManaged: presentation.entry.target._tag === "RelayConnectionTarget",
|
||||
relayManaged: hasRelayRoute(presentation.entry),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,10 @@ export function createRemoteEnvironmentProjectionAtoms(input: {
|
||||
: displayUrl.replace(/^http:/, "ws:")
|
||||
: new URL(socketUrl).origin;
|
||||
const authorization = prepared?.httpAuthorization ?? null;
|
||||
const relayManaged = presentation.entry.target._tag === "RelayConnectionTarget";
|
||||
// Credentials follow the route in use, which may not be the preferred one.
|
||||
const relayManaged = prepared
|
||||
? prepared.target._tag === "RelayConnectionTarget"
|
||||
: presentation.entry.target._tag === "RelayConnectionTarget";
|
||||
|
||||
previousEntry = presentation.entry;
|
||||
previousPrepared = prepared;
|
||||
|
||||
@@ -110,10 +110,10 @@ export function useRemoteConnections() {
|
||||
}, []);
|
||||
|
||||
const onConnectPress = useCallback(
|
||||
async (pairingUrl?: string) => {
|
||||
async (pairingUrl?: string, expectedEnvironmentId?: EnvironmentId) => {
|
||||
const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
|
||||
setPendingConnectionError(null);
|
||||
const result = await controller.connectPairingUrl(nextPairingUrl);
|
||||
const result = await controller.connectPairingUrl(nextPairingUrl, expectedEnvironmentId);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
const message =
|
||||
|
||||
@@ -327,6 +327,7 @@ describe("cloud onboarding discovery", () => {
|
||||
{
|
||||
environmentId: newMachineId,
|
||||
connection: { phase: "connected", error: null, traceId: null },
|
||||
relayManaged: true,
|
||||
},
|
||||
]}
|
||||
showSavedEnvironments
|
||||
|
||||
@@ -48,6 +48,8 @@ function discoveredCompatibilityError(
|
||||
export interface SavedCloudEnvironmentConnection {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly connection: EnvironmentConnectionPresentation;
|
||||
/** False for a machine saved over another route (LAN, Tailscale, SSH) only. */
|
||||
readonly relayManaged: boolean;
|
||||
/** Present once connected; carries the user's icon override. */
|
||||
readonly serverConfig?: ServerConfig | null;
|
||||
}
|
||||
@@ -121,7 +123,15 @@ export function CloudEnvironmentConnectRows({
|
||||
ReadonlySet<EnvironmentId>
|
||||
>(new Set());
|
||||
const savedById = new Map(
|
||||
savedEnvironments.map((environment) => [environment.environmentId, environment]),
|
||||
savedEnvironments
|
||||
.filter((environment) => environment.relayManaged)
|
||||
.map((environment) => [environment.environmentId, environment]),
|
||||
);
|
||||
// Saved over another route only: T3 Connect would be an added fallback.
|
||||
const savedWithoutRelay = new Set(
|
||||
savedEnvironments
|
||||
.filter((environment) => !environment.relayManaged)
|
||||
.map((environment) => environment.environmentId),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -153,8 +163,12 @@ export function CloudEnvironmentConnectRows({
|
||||
if (result._tag === "Success") {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Environment added",
|
||||
description: `Connecting to ${environment.label} through T3 Connect.`,
|
||||
title: savedWithoutRelay.has(environment.environmentId)
|
||||
? "T3 Connect route added"
|
||||
: "Environment added",
|
||||
description: savedWithoutRelay.has(environment.environmentId)
|
||||
? `${environment.label} falls back to T3 Connect when its other routes are unreachable.`
|
||||
: `Connecting to ${environment.label} through T3 Connect.`,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -182,10 +196,14 @@ export function CloudEnvironmentConnectRows({
|
||||
return false;
|
||||
};
|
||||
|
||||
// During onboarding selection a machine saved over another route already
|
||||
// has its own row elsewhere, and selecting it must not add a T3 Connect
|
||||
// route as a side effect, so it is left out here.
|
||||
const visibleEnvironments = [...environmentsState.environments.values()].filter(
|
||||
({ environment }) =>
|
||||
environment.environmentId !== primaryEnvironmentId &&
|
||||
(showSavedEnvironments || !savedById.has(environment.environmentId)),
|
||||
(showSavedEnvironments || !savedById.has(environment.environmentId)) &&
|
||||
!(selection && savedWithoutRelay.has(environment.environmentId)),
|
||||
);
|
||||
const selectNewComputers = useEffectEvent(() => {
|
||||
const seen = selection?.autoSelectedComputers;
|
||||
@@ -337,19 +355,22 @@ export function CloudEnvironmentConnectRows({
|
||||
: availability === "checking"
|
||||
? "bg-warning"
|
||||
: "bg-muted-foreground/35";
|
||||
const notAdded = savedWithoutRelay.has(environment.environmentId)
|
||||
? "Saved without T3 Connect"
|
||||
: "Not added";
|
||||
const statusText =
|
||||
unsupported && !savedEnvironment
|
||||
? "T3 Connect · Not added · Client not supported"
|
||||
? `T3 Connect · ${notAdded} · Client not supported`
|
||||
: savedConnection
|
||||
? savedConnection.statusText
|
||||
: availability === "online"
|
||||
? "T3 Connect · Not added · Relay online"
|
||||
? `T3 Connect · ${notAdded} · Relay online`
|
||||
: availability === "offline"
|
||||
? "T3 Connect · Not added · Relay offline"
|
||||
? `T3 Connect · ${notAdded} · Relay offline`
|
||||
: availability === "checking"
|
||||
? "T3 Connect · Not added · Checking relay status…"
|
||||
? `T3 Connect · ${notAdded} · Checking relay status…`
|
||||
: (Option.getOrNull(error)?.message ??
|
||||
"T3 Connect · Not added · Relay status unavailable");
|
||||
`T3 Connect · ${notAdded} · Relay status unavailable`);
|
||||
if (selection) {
|
||||
return (
|
||||
<label
|
||||
@@ -464,7 +485,11 @@ export function CloudEnvironmentConnectRows({
|
||||
disabled={connectingEnvironmentIds.size > 0}
|
||||
onClick={() => void connectEnvironment(environment)}
|
||||
>
|
||||
{connectingEnvironmentIds.has(environment.environmentId) ? "Adding…" : "Add"}
|
||||
{connectingEnvironmentIds.has(environment.environmentId)
|
||||
? "Adding…"
|
||||
: savedWithoutRelay.has(environment.environmentId)
|
||||
? "Add route"
|
||||
: "Add"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import {
|
||||
ChevronRightIcon,
|
||||
ChevronsLeftRightEllipsisIcon,
|
||||
EllipsisIcon,
|
||||
PlusIcon,
|
||||
QrCodeIcon,
|
||||
RouteIcon,
|
||||
TerminalIcon,
|
||||
} from "lucide-react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
@@ -41,7 +43,12 @@ import {
|
||||
type EnvironmentId,
|
||||
resolveEnvironmentMachineKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { connectionStatusText } from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
RelayConnectionRegistration,
|
||||
RelayConnectionTarget,
|
||||
connectionRoutes,
|
||||
connectionStatusText,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
@@ -69,6 +76,8 @@ import {
|
||||
import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
|
||||
import { searchableSetting } from "./settingsSearch";
|
||||
import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
|
||||
import { EnvironmentRoutesList } from "./EnvironmentRoutesList";
|
||||
import { usePreparedConnection } from "~/state/session";
|
||||
import {
|
||||
EnvironmentRow,
|
||||
environmentTransportLabel,
|
||||
@@ -1433,6 +1442,7 @@ type SavedBackendListRowProps = {
|
||||
removingEnvironmentId: EnvironmentId | null;
|
||||
onSetEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
|
||||
onRemove: (environment: EnvironmentPresentation) => void;
|
||||
onAddRoute: (environment: EnvironmentPresentation) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1482,7 +1492,9 @@ function SavedBackendListRow({
|
||||
removingEnvironmentId,
|
||||
onSetEnabled,
|
||||
onRemove,
|
||||
onAddRoute,
|
||||
}: SavedBackendListRowProps) {
|
||||
const [routesOpen, setRoutesOpen] = useState(false);
|
||||
const environmentId = environment.environmentId;
|
||||
const unsupported = environment.connection.phase === "unsupported";
|
||||
const enabled = environment.entry.enabled && !unsupported;
|
||||
@@ -1537,8 +1549,13 @@ function SavedBackendListRow({
|
||||
environment.serverConfig ??
|
||||
(lastDescriptor === undefined ? null : { environment: lastDescriptor }),
|
||||
);
|
||||
const prepared = usePreparedConnection(environmentId);
|
||||
const routeCount = connectionRoutes(environment.entry).length;
|
||||
const subtitleText = [
|
||||
environmentTransportLabel(environment),
|
||||
environmentTransportLabel(
|
||||
environment,
|
||||
isConnected && prepared._tag === "Some" ? prepared.value.target : null,
|
||||
),
|
||||
resumingServerUpdate ? "Restarting" : status.text,
|
||||
enabled && versionMismatch ? serverVersion : null,
|
||||
]
|
||||
@@ -1571,26 +1588,49 @@ function SavedBackendListRow({
|
||||
label={environment.label}
|
||||
dimmed={!enabled}
|
||||
subtitle={
|
||||
<Tooltip>
|
||||
{/* The status can change while the tooltip is open, and base-ui only
|
||||
re-measures the popup when the trigger's payload changes. */}
|
||||
<TooltipTrigger
|
||||
payload={statusTooltip}
|
||||
render={
|
||||
<span
|
||||
className={cn(
|
||||
"block truncate",
|
||||
enabled && status.tone === "error" && !resumingServerUpdate && "text-destructive",
|
||||
)}
|
||||
/>
|
||||
}
|
||||
<span className="flex min-w-0 items-center gap-1">
|
||||
<Tooltip>
|
||||
{/* The status can change while the tooltip is open, and base-ui only
|
||||
re-measures the popup when the trigger's payload changes. */}
|
||||
<TooltipTrigger
|
||||
payload={statusTooltip}
|
||||
render={
|
||||
<span
|
||||
className={cn(
|
||||
"min-w-0 truncate",
|
||||
enabled &&
|
||||
status.tone === "error" &&
|
||||
!resumingServerUpdate &&
|
||||
"text-destructive",
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{subtitleText}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top" className="whitespace-pre-wrap">
|
||||
{statusTooltip}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<span aria-hidden className="shrink-0">
|
||||
·
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={routesOpen}
|
||||
onClick={() => setRoutesOpen((open) => !open)}
|
||||
className="inline-flex shrink-0 items-center gap-0.5 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
{subtitleText}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top" className="whitespace-pre-wrap">
|
||||
{statusTooltip}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
{routeCount === 1 ? "Routes" : `${routeCount} routes`}
|
||||
<ChevronRightIcon
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"size-3 shrink-0 transition-transform duration-150 motion-reduce:transition-none",
|
||||
routesOpen && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</span>
|
||||
}
|
||||
below={
|
||||
serverUpdateState.status !== "idle" ? (
|
||||
@@ -1599,6 +1639,14 @@ function SavedBackendListRow({
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
detail={
|
||||
routesOpen ? (
|
||||
<EnvironmentRoutesList
|
||||
environment={environment}
|
||||
onAddRoute={() => onAddRoute(environment)}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{unsupported &&
|
||||
environment.entry.serverUpdateRequired === true &&
|
||||
@@ -1659,6 +1707,10 @@ function SavedBackendListRow({
|
||||
environmentId={environmentId}
|
||||
serverConfig={environment.serverConfig}
|
||||
/>
|
||||
<MenuItem onClick={() => setRoutesOpen((open) => !open)}>
|
||||
<RouteIcon />
|
||||
{routesOpen ? "Hide routes" : "Routes"}
|
||||
</MenuItem>
|
||||
{errorTraceId ? (
|
||||
<MenuItem onClick={() => copyTraceId(errorTraceId)}>Copy trace ID</MenuItem>
|
||||
) : null}
|
||||
@@ -1848,6 +1900,10 @@ export function ConnectionsSettings() {
|
||||
reportFailure: false,
|
||||
});
|
||||
const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
|
||||
const registerEnvironment = useAtomCommand(environmentCatalog.register, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const relayDiscoveryState = useRelayEnvironmentDiscovery();
|
||||
const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1974,6 +2030,8 @@ export function ConnectionsSettings() {
|
||||
>(null);
|
||||
const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false);
|
||||
const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false);
|
||||
// Set when the dialog adds a route to a saved machine instead of a new one.
|
||||
const [routeTarget, setRouteTarget] = useState<EnvironmentPresentation | null>(null);
|
||||
const [savedBackendMode, setSavedBackendMode] = useState<"remote" | "ssh">("remote");
|
||||
const [savedBackendHost, setSavedBackendHost] = useState("");
|
||||
const [savedBackendPairingCode, setSavedBackendPairingCode] = useState("");
|
||||
@@ -2316,7 +2374,11 @@ export function ConnectionsSettings() {
|
||||
async (target: DesktopSshEnvironmentTarget) => {
|
||||
setIsAddingSavedBackend(true);
|
||||
setSavedBackendError(null);
|
||||
const result = await connectSshEnvironment({ target, label: "" });
|
||||
const result = await connectSshEnvironment({
|
||||
target,
|
||||
label: "",
|
||||
...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}),
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
setSavedBackendError(formatDesktopSshConnectionError(squashAtomCommandFailure(result)));
|
||||
@@ -2333,12 +2395,14 @@ export function ConnectionsSettings() {
|
||||
setAddBackendDialogOpen(false);
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Environment connected",
|
||||
description: `${target.alias} is ready over an SSH-managed tunnel.`,
|
||||
title: routeTarget ? "Route added" : "Environment connected",
|
||||
description: routeTarget
|
||||
? `${routeTarget.label} can now be reached over SSH ${target.alias}.`
|
||||
: `${target.alias} is ready over an SSH-managed tunnel.`,
|
||||
});
|
||||
setIsAddingSavedBackend(false);
|
||||
},
|
||||
[connectSshEnvironment],
|
||||
[connectSshEnvironment, routeTarget],
|
||||
);
|
||||
|
||||
const handleAddSavedBackend = useCallback(async () => {
|
||||
@@ -2381,7 +2445,10 @@ export function ConnectionsSettings() {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await connectPairing(remotePairingInput);
|
||||
const result = await connectPairing({
|
||||
...remotePairingInput,
|
||||
...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}),
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
@@ -2405,13 +2472,22 @@ export function ConnectionsSettings() {
|
||||
setSavedBackendSshUsername("");
|
||||
setSavedBackendSshPort("");
|
||||
setAddBackendDialogOpen(false);
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Backend added",
|
||||
description: "The environment is saved and will reconnect on app startup.",
|
||||
});
|
||||
toastManager.add(
|
||||
routeTarget
|
||||
? {
|
||||
type: "success",
|
||||
title: "Route added",
|
||||
description: `${routeTarget.label} now has another way to connect.`,
|
||||
}
|
||||
: {
|
||||
type: "success",
|
||||
title: "Backend added",
|
||||
description: "The environment is saved and will reconnect on app startup.",
|
||||
},
|
||||
);
|
||||
setIsAddingSavedBackend(false);
|
||||
}, [
|
||||
routeTarget,
|
||||
connectPairing,
|
||||
connectSavedBackendSshTarget,
|
||||
savedBackendHost,
|
||||
@@ -2703,8 +2779,57 @@ export function ConnectionsSettings() {
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
// T3 Connect is offered as a route when this account can reach the machine
|
||||
// through it and it is not one of the machine's routes yet.
|
||||
const relayRouteOffer =
|
||||
routeTarget !== null &&
|
||||
!routeTarget.relayManaged &&
|
||||
relayDiscoveryState.environments.has(routeTarget.environmentId)
|
||||
? relayDiscoveryState.environments.get(routeTarget.environmentId)!.environment
|
||||
: null;
|
||||
const addRelayRoute = async () => {
|
||||
if (relayRouteOffer === null || routeTarget === null) return;
|
||||
setIsAddingSavedBackend(true);
|
||||
const result = await registerEnvironment(
|
||||
new RelayConnectionRegistration({
|
||||
target: new RelayConnectionTarget({
|
||||
environmentId: relayRouteOffer.environmentId,
|
||||
label: routeTarget.label,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
setIsAddingSavedBackend(false);
|
||||
if (result._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
setSavedBackendError(error instanceof Error ? error.message : "Could not add the route.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
setAddBackendDialogOpen(false);
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Route added",
|
||||
description: `${routeTarget.label} falls back to T3 Connect when its other routes are unreachable.`,
|
||||
});
|
||||
};
|
||||
const renderRemoteModeBody = () => (
|
||||
<div className="space-y-4">
|
||||
{relayRouteOffer !== null ? (
|
||||
<div className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This machine is on your T3 Connect account. Use it as a fallback route.
|
||||
</p>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isAddingSavedBackend}
|
||||
onClick={() => void addRelayRoute()}
|
||||
>
|
||||
Add T3 Connect
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{renderRemoteFields()}
|
||||
{savedBackendError ? <p className="text-xs text-destructive">{savedBackendError}</p> : null}
|
||||
<Button
|
||||
@@ -2714,7 +2839,7 @@ export function ConnectionsSettings() {
|
||||
onClick={() => void handleAddSavedBackend()}
|
||||
>
|
||||
<PlusIcon className="size-3.5" />
|
||||
{isAddingSavedBackend ? "Adding…" : "Add environment"}
|
||||
{isAddingSavedBackend ? "Adding…" : routeTarget ? "Add route" : "Add environment"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
@@ -2835,7 +2960,7 @@ export function ConnectionsSettings() {
|
||||
onClick={() => void handleAddSavedBackend()}
|
||||
>
|
||||
<PlusIcon className="size-3.5" />
|
||||
{isAddingSavedBackend ? "Adding…" : "Add environment"}
|
||||
{isAddingSavedBackend ? "Adding…" : routeTarget ? "Add route" : "Add environment"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -3726,7 +3851,9 @@ export function ConnectionsSettings() {
|
||||
open={addBackendDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setAddBackendDialogOpen(open);
|
||||
if (!open) {
|
||||
if (open) {
|
||||
setRouteTarget(null);
|
||||
} else {
|
||||
setSavedBackendError(null);
|
||||
}
|
||||
}}
|
||||
@@ -3748,8 +3875,14 @@ export function ConnectionsSettings() {
|
||||
</Tooltip>
|
||||
<DialogPopup className="max-h-[80dvh] sm:max-w-3xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Environment</DialogTitle>
|
||||
<DialogDescription>Pair another environment to this client.</DialogDescription>
|
||||
<DialogTitle>
|
||||
{routeTarget ? `Add a route to ${routeTarget.label}` : "Add Environment"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{routeTarget
|
||||
? "Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine."
|
||||
: "Pair another environment to this client."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel>
|
||||
<div className="space-y-4">
|
||||
@@ -3787,6 +3920,11 @@ export function ConnectionsSettings() {
|
||||
removingEnvironmentId={removingSavedEnvironmentId}
|
||||
onSetEnabled={handleSetSavedBackendEnabled}
|
||||
onRemove={handleRemoveSavedBackend}
|
||||
onAddRoute={(target) => {
|
||||
setRouteTarget(target);
|
||||
setSavedBackendError(null);
|
||||
setAddBackendDialogOpen(true);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<CloudRemoteEnvironmentRows
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import {
|
||||
DndContext,
|
||||
type DragEndEvent,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
closestCenter,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from "@dnd-kit/core";
|
||||
import { restrictToParentElement, restrictToVerticalAxis } from "@dnd-kit/modifiers";
|
||||
import {
|
||||
SortableContext,
|
||||
arrayMove,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import {
|
||||
type ConnectionRoute,
|
||||
connectionRouteAddress,
|
||||
connectionRouteId,
|
||||
connectionRouteLabel,
|
||||
connectionRoutes,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { GripVerticalIcon, PlusIcon, XIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { requestConfirmDialog } from "~/confirmDialog";
|
||||
import { environmentCatalog } from "~/connection/catalog";
|
||||
import { cn } from "~/lib/utils";
|
||||
import type { EnvironmentPresentation } from "~/state/environments";
|
||||
import { usePreparedConnection } from "~/state/session";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { Button } from "../ui/button";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
/**
|
||||
* The ways this client reaches one saved machine, preferred first. Drag to
|
||||
* reorder; the first route that answers is used and the connection moves back
|
||||
* up when a better one is reachable again. Shown under the machine's row.
|
||||
*/
|
||||
export function EnvironmentRoutesList({
|
||||
environment,
|
||||
onAddRoute,
|
||||
}: {
|
||||
readonly environment: EnvironmentPresentation;
|
||||
readonly onAddRoute: () => void;
|
||||
}) {
|
||||
const saved = connectionRoutes(environment.entry);
|
||||
const savedIds = saved.map((route) => connectionRouteId(route.target));
|
||||
// A dropped order shows until the catalog matches it, so the row does not
|
||||
// jump back while the reorder is being saved.
|
||||
const [pending, setPending] = useState<ReadonlyArray<string> | null>(null);
|
||||
const order: Array<string> =
|
||||
pending !== null &&
|
||||
pending.length === savedIds.length &&
|
||||
pending.some((id, index) => id !== savedIds[index])
|
||||
? [...pending]
|
||||
: savedIds;
|
||||
const byId = new Map(saved.map((route) => [connectionRouteId(route.target), route]));
|
||||
const routes = order.flatMap((id) => byId.get(id) ?? []);
|
||||
|
||||
const prepared = usePreparedConnection(environment.environmentId);
|
||||
const activeRouteId =
|
||||
prepared._tag === "Some" && environment.connection.phase === "connected"
|
||||
? connectionRouteId(prepared.value.target)
|
||||
: null;
|
||||
const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "Reorder routes");
|
||||
const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "Remove route");
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
|
||||
// Removing a paired route forgets its credential, so it asks first, like
|
||||
// on mobile. No mounted confirm host means no removal.
|
||||
const confirmRemove = async (route: ConnectionRoute) => {
|
||||
const address = connectionRouteAddress(route);
|
||||
const confirmed = await requestConfirmDialog(
|
||||
`Remove ${connectionRouteLabel(route)} route?${address === null ? "" : `\n${address}`}`,
|
||||
{ variant: "destructive" },
|
||||
);
|
||||
if (confirmed !== true) return;
|
||||
await removeRoute({
|
||||
environmentId: environment.environmentId,
|
||||
routeId: connectionRouteId(route.target),
|
||||
});
|
||||
};
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
if (event.over === null || event.active.id === event.over.id) return;
|
||||
const next = arrayMove(
|
||||
order,
|
||||
order.indexOf(String(event.active.id)),
|
||||
order.indexOf(String(event.over.id)),
|
||||
);
|
||||
setPending(next);
|
||||
void reorder({ environmentId: environment.environmentId, routeIds: next }).then((result) => {
|
||||
if (result._tag === "Failure") setPending(null);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mt-2 rounded-md border border-border/70">
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext items={order} strategy={verticalListSortingStrategy}>
|
||||
<ol aria-label={`Routes to ${environment.label}, preferred first`}>
|
||||
{routes.map((route, index) => (
|
||||
<SortableRouteRow
|
||||
key={connectionRouteId(route.target)}
|
||||
route={route}
|
||||
position={index + 1}
|
||||
inUse={connectionRouteId(route.target) === activeRouteId}
|
||||
// The last route goes with the machine; that is "Remove from
|
||||
// this device", not a route action.
|
||||
removable={routes.length > 1}
|
||||
onRemove={() => void confirmRemove(route)}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
<div className="border-t border-border/70 px-1 py-1">
|
||||
<Button size="xs" variant="ghost-muted" onClick={onAddRoute}>
|
||||
<PlusIcon className="size-3" />
|
||||
Add route
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SortableRouteRow({
|
||||
route,
|
||||
position,
|
||||
inUse,
|
||||
removable,
|
||||
onRemove,
|
||||
}: {
|
||||
readonly route: ConnectionRoute;
|
||||
readonly position: number;
|
||||
readonly inUse: boolean;
|
||||
readonly removable: boolean;
|
||||
readonly onRemove: () => void;
|
||||
}) {
|
||||
const id = connectionRouteId(route.target);
|
||||
const label = connectionRouteLabel(route);
|
||||
const address = connectionRouteAddress(route);
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
setActivatorNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id });
|
||||
|
||||
return (
|
||||
<li
|
||||
ref={setNodeRef}
|
||||
style={{ transform: CSS.Translate.toString(transform), transition }}
|
||||
className={cn(
|
||||
"flex items-center gap-2 border-b border-border/70 px-1 py-1.5 last:border-b-0",
|
||||
isDragging && "relative z-10 rounded-md bg-background shadow-md",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
ref={setActivatorNodeRef}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
aria-label={`Reorder ${label}, position ${position}`}
|
||||
className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted-foreground/70 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
|
||||
>
|
||||
<GripVerticalIcon className="size-3.5" />
|
||||
</button>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="flex items-center gap-1.5 text-xs font-medium text-foreground">
|
||||
{label}
|
||||
{inUse ? (
|
||||
<span className="rounded-sm bg-success/12 px-1 text-2xs font-normal text-success-foreground">
|
||||
In use
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
{address !== null ? (
|
||||
<p className="truncate text-2xs text-muted-foreground">
|
||||
{address}
|
||||
{isLearnedRoute(route) ? " · found automatically" : ""}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
{removable ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-muted"
|
||||
size="icon-xs"
|
||||
aria-label={`Remove ${label} route`}
|
||||
onClick={onRemove}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Remove route</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function isLearnedRoute(route: ConnectionRoute): boolean {
|
||||
return (
|
||||
route.profile._tag === "Some" &&
|
||||
route.profile.value._tag === "BearerConnectionProfile" &&
|
||||
"learned" in route.profile.value &&
|
||||
route.profile.value.learned === true
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
type ConnectionTarget,
|
||||
connectionRouteId,
|
||||
connectionRouteLabel,
|
||||
connectionRoutes,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import type { DesktopSshEnvironmentTarget, EnvironmentMachineKind } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import type { ReactNode } from "react";
|
||||
@@ -15,10 +21,26 @@ export function formatDesktopSshTarget(target: DesktopSshEnvironmentTarget): str
|
||||
/**
|
||||
* How this client reaches a machine, printed first in every environment row so
|
||||
* T3 Connect, SSH, WSL, and plain remote links are told apart without a legend.
|
||||
* A machine with several routes names the one in use, or how many it has.
|
||||
*/
|
||||
export function environmentTransportLabel(environment: EnvironmentPresentation): string {
|
||||
export function environmentTransportLabel(
|
||||
environment: EnvironmentPresentation,
|
||||
activeTarget: ConnectionTarget | null = null,
|
||||
): string {
|
||||
const { entry } = environment;
|
||||
if (entry.target._tag === "PrimaryConnectionTarget") return "This machine";
|
||||
const routes = connectionRoutes(entry);
|
||||
if (routes.length > 1) {
|
||||
const active =
|
||||
activeTarget === null
|
||||
? undefined
|
||||
: routes.find(
|
||||
(route) => connectionRouteId(route.target) === connectionRouteId(activeTarget),
|
||||
);
|
||||
return active === undefined
|
||||
? connectionRouteLabel(routes[0]!)
|
||||
: `via ${connectionRouteLabel(active)}`;
|
||||
}
|
||||
if (environment.relayManaged) return "T3 Connect";
|
||||
if (isDesktopLocalConnectionTarget(entry.target)) return "WSL";
|
||||
if (
|
||||
@@ -41,6 +63,7 @@ export function EnvironmentRow({
|
||||
label,
|
||||
subtitle,
|
||||
below,
|
||||
detail,
|
||||
dimmed = false,
|
||||
className,
|
||||
children,
|
||||
@@ -50,6 +73,8 @@ export function EnvironmentRow({
|
||||
readonly subtitle: ReactNode;
|
||||
/** Extra content under the subtitle, such as update progress. */
|
||||
readonly below?: ReactNode;
|
||||
/** Expanded content under the whole row, aligned with the label, such as its routes. */
|
||||
readonly detail?: ReactNode;
|
||||
readonly dimmed?: boolean;
|
||||
readonly className?: string;
|
||||
readonly children?: ReactNode;
|
||||
@@ -69,6 +94,7 @@ export function EnvironmentRow({
|
||||
{below}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">{children}</div>
|
||||
{detail ? <div className="col-span-2 col-start-2 min-w-0">{detail}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,14 +15,9 @@ export const connectPairing = createRuntimeCommand(connectionAtomRuntime, {
|
||||
scheduler: onboardingScheduler,
|
||||
concurrency: {
|
||||
mode: "singleFlight",
|
||||
key: (input: { pairingUrl?: string; host?: string; pairingCode?: string }) =>
|
||||
JSON.stringify(input),
|
||||
key: (input: ConnectionOnboarding.PairingConnectionInput) => JSON.stringify(input),
|
||||
},
|
||||
execute: (input: {
|
||||
readonly pairingUrl?: string;
|
||||
readonly host?: string;
|
||||
readonly pairingCode?: string;
|
||||
}) =>
|
||||
execute: (input: ConnectionOnboarding.PairingConnectionInput) =>
|
||||
ConnectionOnboarding.ConnectionOnboarding.pipe(
|
||||
Effect.flatMap((onboarding) => onboarding.registerPairing(input)),
|
||||
),
|
||||
@@ -35,7 +30,7 @@ export const connectSshEnvironment = createRuntimeCommand(connectionAtomRuntime,
|
||||
mode: "serial",
|
||||
key: (input: { readonly target: DesktopSshEnvironmentTarget }) => JSON.stringify(input.target),
|
||||
},
|
||||
execute: (input: { readonly target: DesktopSshEnvironmentTarget; readonly label?: string }) =>
|
||||
execute: (input: ConnectionOnboarding.SshConnectionInput) =>
|
||||
ConnectionOnboarding.ConnectionOnboarding.pipe(
|
||||
Effect.flatMap((onboarding) => onboarding.registerSsh(input)),
|
||||
),
|
||||
|
||||
@@ -83,6 +83,21 @@ describe("desktop SSH pairing", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not consume the credential when adding a route to a different machine", () =>
|
||||
Effect.gen(function* () {
|
||||
const calls: string[] = [];
|
||||
|
||||
const error = yield* provisionDesktopSshEnvironment(
|
||||
makeBridge(calls),
|
||||
TARGET,
|
||||
EnvironmentId.make("some-other-machine"),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({ reason: "configuration" });
|
||||
expect(calls).toEqual(["ensure", "descriptor"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not consume the credential when descriptor discovery fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const calls: string[] = [];
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
type DesktopBridge,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
type DesktopSshEnvironmentTarget,
|
||||
type EnvironmentId,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
@@ -87,28 +88,68 @@ const connectivityLayer = Connectivity.layer({
|
||||
),
|
||||
});
|
||||
|
||||
interface NetworkInformationLike extends EventTarget {
|
||||
readonly type?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wakes connections when the browser reports a different network type, such
|
||||
* as a laptop moving from Wi-Fi to a phone hotspot. `change` also fires for
|
||||
* bandwidth and latency estimates on the same network, so only a type change
|
||||
* counts. Browsers without `navigator.connection.type` rely on the periodic
|
||||
* route check instead.
|
||||
*/
|
||||
const networkPathChanges = Stream.callback<"network-changed">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const connection =
|
||||
typeof navigator === "undefined"
|
||||
? undefined
|
||||
: (navigator as Navigator & { readonly connection?: NetworkInformationLike }).connection;
|
||||
if (connection?.type === undefined) return undefined;
|
||||
let previous = connection.type;
|
||||
const listener = () => {
|
||||
const type = connection.type;
|
||||
if (type === undefined || type === previous) return;
|
||||
previous = type;
|
||||
Queue.offerUnsafe(queue, "network-changed");
|
||||
};
|
||||
connection.addEventListener("change", listener);
|
||||
return { connection, listener };
|
||||
}),
|
||||
(subscription) =>
|
||||
Effect.sync(() =>
|
||||
subscription?.connection.removeEventListener("change", subscription.listener),
|
||||
),
|
||||
).pipe(Effect.asVoid),
|
||||
);
|
||||
|
||||
const wakeupsLayer = Wakeups.layer({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const listener = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
Queue.offerUnsafe(queue, "application-active");
|
||||
}
|
||||
};
|
||||
document.addEventListener("visibilitychange", listener);
|
||||
return listener;
|
||||
}),
|
||||
(listener) =>
|
||||
changes: Stream.mergeAll(
|
||||
[
|
||||
Stream.callback<"application-active">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
document.removeEventListener("visibilitychange", listener);
|
||||
const listener = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
Queue.offerUnsafe(queue, "application-active");
|
||||
}
|
||||
};
|
||||
document.addEventListener("visibilitychange", listener);
|
||||
return listener;
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
),
|
||||
(listener) =>
|
||||
Effect.sync(() => {
|
||||
document.removeEventListener("visibilitychange", listener);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
),
|
||||
networkPathChanges,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
});
|
||||
|
||||
@@ -141,7 +182,11 @@ function sshPreparationError(cause: unknown) {
|
||||
|
||||
export const provisionDesktopSshEnvironment = Effect.fn(
|
||||
"web.connectionPlatform.ssh.provisionDesktop",
|
||||
)(function* (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) {
|
||||
)(function* (
|
||||
bridge: DesktopBridge,
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
expectedEnvironmentId?: EnvironmentId,
|
||||
) {
|
||||
const bootstrap = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
bridge.ensureSshEnvironment(target, {
|
||||
@@ -160,6 +205,12 @@ export const provisionDesktopSshEnvironment = Effect.fn(
|
||||
try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
|
||||
catch: sshPreparationError,
|
||||
});
|
||||
if (expectedEnvironmentId !== undefined && descriptor.environmentId !== expectedEnvironmentId) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "configuration",
|
||||
detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,
|
||||
});
|
||||
}
|
||||
const access = yield* Effect.tryPromise({
|
||||
try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
|
||||
catch: sshPreparationError,
|
||||
@@ -222,16 +273,18 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
}).pipe(Effect.map(Option.fromNullishOr)),
|
||||
});
|
||||
const ssh = ClientCapabilities.SshEnvironmentGateway.of({
|
||||
provision: Effect.fn("web.connectionPlatform.ssh.provision")(function* (target) {
|
||||
const bridge = window.desktopBridge;
|
||||
if (bridge === undefined) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "unsupported",
|
||||
detail: "SSH environments are only available in the desktop app.",
|
||||
});
|
||||
}
|
||||
return yield* provisionDesktopSshEnvironment(bridge, target);
|
||||
}),
|
||||
provision: Effect.fn("web.connectionPlatform.ssh.provision")(
|
||||
function* (target, expectedEnvironmentId) {
|
||||
const bridge = window.desktopBridge;
|
||||
if (bridge === undefined) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "unsupported",
|
||||
detail: "SSH environments are only available in the desktop app.",
|
||||
});
|
||||
}
|
||||
return yield* provisionDesktopSshEnvironment(bridge, target, expectedEnvironmentId);
|
||||
},
|
||||
),
|
||||
prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
|
||||
const bridge = window.desktopBridge;
|
||||
if (bridge === undefined) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
removeCatalogValue,
|
||||
removeConnectionFromCatalog,
|
||||
setConnectionEnabledInCatalog,
|
||||
setRoutesInCatalog,
|
||||
replaceCatalogValue,
|
||||
Persistence,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
@@ -86,6 +87,7 @@ function persistenceError(
|
||||
| "list-targets"
|
||||
| "list-disabled-targets"
|
||||
| "register-connection"
|
||||
| "set-connection-routes"
|
||||
| "remove-connection"
|
||||
| "set-connection-enabled"
|
||||
| "load-shell"
|
||||
@@ -474,13 +476,17 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
});
|
||||
const registrationStore = Persistence.ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
register: (registration, routes) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.update((document) => registerConnectionInCatalog(document, registration, routes))
|
||||
.pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
|
||||
remove: (target) =>
|
||||
setRoutes: (environmentId, routes) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.update((document) => setRoutesInCatalog(document, environmentId, routes))
|
||||
.pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause))),
|
||||
remove: (environmentId) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, environmentId))
|
||||
.pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
|
||||
setEnabled: (environmentId, enabled) =>
|
||||
catalog
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
|
||||
import { type ConnectionCatalogEntry, hasRelayRoute } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
interface OnboardingEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly connection: { readonly phase: string };
|
||||
readonly entry: { readonly target: ConnectionTarget };
|
||||
readonly entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">;
|
||||
}
|
||||
|
||||
export function isOnboardingRelayEnvironment(
|
||||
environment: Pick<OnboardingEnvironment, "entry">,
|
||||
): boolean {
|
||||
return environment.entry.target._tag === "RelayConnectionTarget";
|
||||
return hasRelayRoute(environment.entry);
|
||||
}
|
||||
|
||||
/** Keep a directly paired machine pinned while its initial connection completes. */
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
connectionCatalogDisplayUrl,
|
||||
hasRelayRoute,
|
||||
type EnvironmentPresentation as BaseEnvironmentPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { Discovery } from "@t3tools/client-runtime/relay";
|
||||
@@ -34,7 +35,7 @@ function projectEnvironmentPresentation(
|
||||
environmentId,
|
||||
label: presentation.entry.target.label,
|
||||
displayUrl: connectionCatalogDisplayUrl(presentation.entry),
|
||||
relayManaged: presentation.entry.target._tag === "RelayConnectionTarget",
|
||||
relayManaged: hasRelayRoute(presentation.entry),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,24 @@ prove that a route works. In particular, a host's loopback address refers to a
|
||||
different machine when another device opens it. Endpoint selection must not
|
||||
silently fall back to loopback when a shareable endpoint is unavailable.
|
||||
|
||||
A saved environment holds an ordered list of routes, and the
|
||||
[driver](../../packages/client-runtime/src/connection/driver.ts) connects over
|
||||
the first that works. Each direct route is first checked with the public
|
||||
descriptor, so a saved LAN address that a different machine answers on another
|
||||
network receives no credential. That check is not proof of a working route:
|
||||
when every route stays silent, each is still tried. A route that fails to
|
||||
connect, including a blocked one such as a signed-out T3 Connect, moves on to
|
||||
the next; only an incompatible server stops the walk, because it is the same
|
||||
server on every route. While connected over a later route the
|
||||
[supervisor](../../packages/client-runtime/src/connection/supervisor.ts)
|
||||
preflights the earlier ones and replaces the session when one would connect.
|
||||
Preflight includes authorization so a route that answers but rejects this
|
||||
client never costs a working session; a route that still fails afterwards is
|
||||
held back for a cooldown so a flaky network cannot bounce the connection.
|
||||
|
||||
GitHub routing trust covers the whole route list. Adding or changing a route
|
||||
revokes it; reordering does not, because the same addresses remain trusted.
|
||||
|
||||
## Hosted web is a client
|
||||
|
||||
The hosted web app stores its connection catalog in the browser and connects
|
||||
|
||||
@@ -62,6 +62,26 @@ created in Settings can only be copied from the client that created them while
|
||||
its Connections page stays open. If you leave or reload that page, create
|
||||
another link to share.
|
||||
|
||||
### Reach one machine several ways
|
||||
|
||||
A machine can have more than one route: LAN, Tailscale, a public URL, SSH, or
|
||||
T3 Connect. To add one, choose **Add route** in the machine's route list, or
|
||||
next to it in the T3 Connect list. Pairing the same machine again over another
|
||||
address also adds a route instead of a second machine. A new route is placed by
|
||||
speed, in that order, and you can reorder routes at any time.
|
||||
|
||||
T3 Code connects over the first route that answers. Away from home, a LAN
|
||||
address that does not answer is checked briefly and skipped. It is only tried
|
||||
again, after the other routes, if none of them connect. While connected over a
|
||||
later route, T3 Code checks the earlier ones when your network changes, when you
|
||||
return to the app, and every minute, and moves back as soon as one works.
|
||||
|
||||
On web and desktop, select the route count under the machine's name in
|
||||
**Settings → Connections** to see its routes. Drag a route to change the order,
|
||||
or remove it. On mobile, open the machine under **Settings → Environments** and
|
||||
choose **Edit**. Signing out of T3 Connect removes only that route; a machine
|
||||
you can still reach another way stays saved.
|
||||
|
||||
### Balance new threads across machines
|
||||
|
||||
Auto balance is off by default. On web and desktop, enable it in
|
||||
|
||||
@@ -36,9 +36,21 @@ export class SshConnectionProfile extends Schema.TaggedClass<SshConnectionProfil
|
||||
export const ConnectionProfile = Schema.Union([BearerConnectionProfile, SshConnectionProfile]);
|
||||
export type ConnectionProfile = typeof ConnectionProfile.Type;
|
||||
|
||||
/** One way to reach an environment: T3 Connect, a direct URL, or SSH. */
|
||||
export interface ConnectionRoute {
|
||||
readonly target: ConnectionTarget;
|
||||
readonly profile: Option.Option<ConnectionProfile>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A saved environment. `target` and `profile` are its preferred route;
|
||||
* `alternateRoutes` holds the others in preference order. Read them together
|
||||
* with `connectionRoutes`.
|
||||
*/
|
||||
export interface ConnectionCatalogEntry {
|
||||
readonly target: ConnectionTarget;
|
||||
readonly profile: Option.Option<ConnectionProfile>;
|
||||
readonly alternateRoutes?: ReadonlyArray<ConnectionRoute>;
|
||||
/** False when the user switched the environment off: saved, but never connects. */
|
||||
readonly enabled: boolean;
|
||||
/** Discovery rejection stays visible while the saved connection is switched off. */
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import type { ConnectionCatalogEntry } from "./catalog.ts";
|
||||
import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
|
||||
import type {
|
||||
ConnectionAttemptError,
|
||||
ConnectionAttemptStage,
|
||||
PreparedConnection,
|
||||
} from "./model.ts";
|
||||
import { ConnectionTransientError } from "./model.ts";
|
||||
import * as ConnectionResolver from "./resolver.ts";
|
||||
import { connectionRoutes, routeEntry, routeHttpBaseUrl } from "./routes.ts";
|
||||
import * as RpcSession from "../rpc/session.ts";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
|
||||
|
||||
export type ConnectionDriverProgress =
|
||||
| {
|
||||
@@ -26,6 +32,15 @@ export interface EnvironmentConnectionLease {
|
||||
readonly session: RpcSession.RpcSession;
|
||||
}
|
||||
|
||||
/**
|
||||
* The result of an unauthenticated reachability check. T3 Connect and SSH
|
||||
* routes have no cheap check, so they are "unchecked".
|
||||
*/
|
||||
export type RouteCheck = "answered" | "silent" | "unchecked";
|
||||
|
||||
/** How long a direct route has to answer before it counts as unreachable from here. */
|
||||
const ROUTE_CHECK_TIMEOUT_MS = 2_500;
|
||||
|
||||
export class ConnectionDriver extends Context.Service<
|
||||
ConnectionDriver,
|
||||
{
|
||||
@@ -33,13 +48,118 @@ export class ConnectionDriver extends Context.Service<
|
||||
entry: ConnectionCatalogEntry,
|
||||
reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
|
||||
) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope>;
|
||||
/** Whether a direct route answers as the entry's environment, without credentials. */
|
||||
readonly checkRoute: (
|
||||
entry: ConnectionCatalogEntry,
|
||||
route: ConnectionRoute,
|
||||
) => Effect.Effect<RouteCheck>;
|
||||
/**
|
||||
* Whether a direct route answers and accepts this client's credential,
|
||||
* without opening a socket. Switching to a route that fails this would
|
||||
* drop a working connection for nothing.
|
||||
*/
|
||||
readonly preflight: (
|
||||
entry: ConnectionCatalogEntry,
|
||||
route: ConnectionRoute,
|
||||
) => Effect.Effect<boolean>;
|
||||
}
|
||||
>()("@t3tools/client-runtime/connection/driver/ConnectionDriver") {}
|
||||
|
||||
/**
|
||||
* Connects over the first route, in preference order, that is worth trying.
|
||||
* Every route is checked at once, but a route only waits for its own check,
|
||||
* so a reachable LAN address connects without waiting on a silent tailnet
|
||||
* one. A silent route is skipped on the first pass so a LAN address from
|
||||
* another network costs one short check, not a connection timeout. A route
|
||||
* that fails to connect moves on to the next: a signed-out T3 Connect must
|
||||
* not hide a working LAN. Silent routes are tried last, since a check is not
|
||||
* proof.
|
||||
*
|
||||
* The reported error is a transient one when any route failed transiently,
|
||||
* so the supervisor keeps retrying a route that may come back; a blocked
|
||||
* error is reported only when every attempted route was blocked.
|
||||
*/
|
||||
export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")(function* <R>(
|
||||
entry: ConnectionCatalogEntry,
|
||||
checkRoute: (route: ConnectionRoute) => Effect.Effect<RouteCheck>,
|
||||
connectRoute: (
|
||||
route: ConnectionRoute,
|
||||
) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, R | Scope.Scope>,
|
||||
) {
|
||||
const routes = connectionRoutes(entry);
|
||||
const checks =
|
||||
routes.length === 1
|
||||
? []
|
||||
: yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));
|
||||
const attemptScope = yield* Scope.Scope;
|
||||
let transient: ConnectionAttemptError | undefined;
|
||||
let blocked: ConnectionAttemptError | undefined;
|
||||
// Each route gets its own scope so a half-open session closes before the next try.
|
||||
const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {
|
||||
const routeScope = yield* Scope.fork(attemptScope);
|
||||
const result = yield* connectRoute(route).pipe(
|
||||
Scope.provide(routeScope),
|
||||
Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),
|
||||
Effect.result,
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
if (result.failure._tag === "ConnectionTransientError") transient ??= result.failure;
|
||||
else blocked ??= result.failure;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
const silent: Array<ConnectionRoute> = [];
|
||||
for (const [index, route] of routes.entries()) {
|
||||
const check = checks.length === 0 ? "unchecked" : yield* Fiber.join(checks[index]!);
|
||||
if (check === "silent") {
|
||||
silent.push(route);
|
||||
continue;
|
||||
}
|
||||
const result = yield* attempt(route);
|
||||
if (result._tag === "Success") return result.success;
|
||||
// An incompatible server is the same server on every route.
|
||||
if (result.failure.reason === "unsupported") return yield* result.failure;
|
||||
}
|
||||
for (const route of silent) {
|
||||
const result = yield* attempt(route);
|
||||
if (result._tag === "Success") return result.success;
|
||||
if (result.failure.reason === "unsupported") return yield* result.failure;
|
||||
}
|
||||
return yield* (
|
||||
transient ??
|
||||
blocked ??
|
||||
new ConnectionTransientError({
|
||||
reason: "endpoint-unavailable",
|
||||
detail: `${entry.target.label} did not answer on any saved route.`,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
/** @public Service construction is part of the canonical Effect module API. */
|
||||
export const make = Effect.gen(function* () {
|
||||
const resolver = yield* ConnectionResolver.ConnectionResolver;
|
||||
const sessions = yield* RpcSession.RpcSessionFactory;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
|
||||
const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
|
||||
const httpBaseUrl = routeHttpBaseUrl(route);
|
||||
if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
|
||||
// The descriptor is public, so this sends no credential to whatever
|
||||
// answers at a saved LAN address on a different network.
|
||||
return fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl,
|
||||
timeoutMs: ROUTE_CHECK_TIMEOUT_MS,
|
||||
}).pipe(
|
||||
Effect.map((descriptor): RouteCheck =>
|
||||
descriptor.environmentId === entry.target.environmentId ? "answered" : "silent",
|
||||
),
|
||||
Effect.orElseSucceed((): RouteCheck => "silent"),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.withSpan("ConnectionDriver.checkRoute", {
|
||||
attributes: { "connection.target.kind": route.target._tag },
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const connect = Effect.fn("ConnectionDriver.connect")(function* (
|
||||
entry: ConnectionCatalogEntry,
|
||||
@@ -49,17 +169,37 @@ export const make = Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"connection.environment.id": target.environmentId,
|
||||
"connection.target.kind": target._tag,
|
||||
"connection.route.count": connectionRoutes(entry).length,
|
||||
});
|
||||
yield* reportProgress({ stage: "preparing" });
|
||||
const prepared = yield* resolver.prepare(entry);
|
||||
yield* reportProgress({ stage: "opening", prepared });
|
||||
const session = yield* sessions.connect(prepared);
|
||||
yield* reportProgress({ stage: "synchronizing", prepared });
|
||||
yield* session.ready;
|
||||
return { prepared, session } satisfies EnvironmentConnectionLease;
|
||||
return yield* connectOverRoutes(
|
||||
entry,
|
||||
(route) => checkRoute(entry, route),
|
||||
Effect.fnUntraced(function* (route) {
|
||||
const prepared = yield* resolver.prepare(routeEntry(entry, route));
|
||||
yield* reportProgress({ stage: "opening", prepared });
|
||||
const session = yield* sessions.connect(prepared);
|
||||
yield* reportProgress({ stage: "synchronizing", prepared });
|
||||
yield* session.ready;
|
||||
return { prepared, session } satisfies EnvironmentConnectionLease;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return ConnectionDriver.of({ connect });
|
||||
const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
|
||||
checkRoute(entry, route).pipe(
|
||||
Effect.flatMap((check) =>
|
||||
check === "answered"
|
||||
? resolver.prepare(routeEntry(entry, route)).pipe(
|
||||
Effect.as(true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
)
|
||||
: Effect.succeed(false),
|
||||
),
|
||||
Effect.withSpan("ConnectionDriver.preflight"),
|
||||
);
|
||||
|
||||
return ConnectionDriver.of({ connect, checkRoute, preflight });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ConnectionDriver, make);
|
||||
@@ -19,9 +19,25 @@ export const StoredGitHubRoutingPermission = Schema.Struct({
|
||||
});
|
||||
export type StoredGitHubRoutingPermission = typeof StoredGitHubRoutingPermission.Type;
|
||||
|
||||
/** Trust belongs to the saved endpoint, never to an environment id advertised by a server alone. */
|
||||
/**
|
||||
* Trust belongs to the saved endpoints, never to an environment id advertised
|
||||
* by a server alone. With several routes the key covers all of them, sorted so
|
||||
* reordering keeps trust but adding or changing an address revokes it.
|
||||
*/
|
||||
export function gitHubRoutingConnectionKey(entry: ConnectionCatalogEntry): string | null {
|
||||
const target = entry.target;
|
||||
const alternates = entry.alternateRoutes ?? [];
|
||||
if (alternates.length === 0) return routeConnectionKey(entry.target, entry.profile);
|
||||
const keys = [{ target: entry.target, profile: entry.profile }, ...alternates].map((route) =>
|
||||
routeConnectionKey(route.target, route.profile),
|
||||
);
|
||||
return keys.every((key) => key !== null) ? JSON.stringify([...keys].sort()) : null;
|
||||
}
|
||||
|
||||
function routeConnectionKey(
|
||||
target: ConnectionCatalogEntry["target"],
|
||||
routeProfile: ConnectionCatalogEntry["profile"],
|
||||
): string | null {
|
||||
const entry = { profile: routeProfile };
|
||||
if (target._tag === "RelayConnectionTarget")
|
||||
return JSON.stringify([target._tag, target.environmentId]);
|
||||
const profile = Option.getOrNull(entry.profile);
|
||||
|
||||
@@ -9,6 +9,8 @@ export * from "./model.ts";
|
||||
export * as ConnectionOnboarding from "./onboarding.ts";
|
||||
export * from "./presentation.ts";
|
||||
export * as ProfileStore from "./profileStore.ts";
|
||||
export * from "./routes.ts";
|
||||
export { type RouteCheck } from "./driver.ts";
|
||||
export * as EnvironmentRegistry from "./registry.ts";
|
||||
// Flat so consumers' inferred types can name them.
|
||||
export { EnvironmentNotRegisteredError, PlatformEnvironmentRemovalError } from "./registry.ts";
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as ConnectionResolver from "./resolver.ts";
|
||||
import * as ConnectionDriver from "./driver.ts";
|
||||
import * as EnvironmentRegistry from "./registry.ts";
|
||||
import * as ConnectionOnboarding from "./onboarding.ts";
|
||||
import { connectionRoutes, hasRelayRoute } from "./routes.ts";
|
||||
import * as PlatformConnectionSource from "../platform/source.ts";
|
||||
import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
|
||||
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
|
||||
@@ -43,7 +44,13 @@ export const watchDiscoveredCompatibility = Effect.fn("connection.watchDiscovere
|
||||
// a different server with the same environment id, such as a
|
||||
// preview app that shares the home directory. Its socket handshake
|
||||
// already checks the protocol.
|
||||
if (registered.get(environmentId)?.target._tag !== "RelayConnectionTarget") continue;
|
||||
const saved = registered.get(environmentId);
|
||||
if (
|
||||
saved === undefined ||
|
||||
connectionRoutes(saved).length !== 1 ||
|
||||
!hasRelayRoute(saved)
|
||||
)
|
||||
continue;
|
||||
const previous = seenChecks.get(environmentId);
|
||||
const fresh =
|
||||
previous?.checkedAt !== status.checkedAt ||
|
||||
|
||||
@@ -98,12 +98,12 @@ describe("connection onboarding", () => {
|
||||
target: {
|
||||
environmentId: "environment-paired",
|
||||
label: "Paired environment",
|
||||
connectionId: "bearer:environment-paired",
|
||||
connectionId: "bearer:environment-paired:https://remote.example.test",
|
||||
},
|
||||
profile: {
|
||||
environmentId: "environment-paired",
|
||||
label: "Paired environment",
|
||||
connectionId: "bearer:environment-paired",
|
||||
connectionId: "bearer:environment-paired:https://remote.example.test",
|
||||
httpBaseUrl: "https://remote.example.test/",
|
||||
wsBaseUrl: "wss://remote.example.test/",
|
||||
},
|
||||
@@ -150,6 +150,25 @@ describe("connection onboarding", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses to add a route that reaches a different machine, keeping the code", () =>
|
||||
Effect.gen(function* () {
|
||||
const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
|
||||
const error = yield* preparePairingRegistration({
|
||||
host: "remote.example.test",
|
||||
pairingCode: "pairing-token",
|
||||
expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(CLIENT_PRESENTATION_LAYER, pairingHttpLayer(calls))),
|
||||
Effect.flip,
|
||||
);
|
||||
expect(error).toMatchObject({ reason: "configuration" });
|
||||
expect(error.message).toContain("different machine");
|
||||
expect(calls.map((call) => call.url)).toEqual([
|
||||
"https://remote.example.test/.well-known/t3/environment",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pairs an outdated server so it can be updated from this client", () =>
|
||||
Effect.gen(function* () {
|
||||
const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
|
||||
@@ -321,12 +340,12 @@ describe("connection onboarding", () => {
|
||||
target: {
|
||||
environmentId: "environment-ssh",
|
||||
label: "Remote development box",
|
||||
connectionId: "ssh:environment-ssh",
|
||||
connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
|
||||
},
|
||||
profile: {
|
||||
environmentId: "environment-ssh",
|
||||
label: "Remote development box",
|
||||
connectionId: "ssh:environment-ssh",
|
||||
connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
|
||||
target,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -32,16 +32,24 @@ import {
|
||||
import * as Persistence from "../platform/persistence.ts";
|
||||
import * as EnvironmentRegistry from "./registry.ts";
|
||||
import { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
|
||||
import { connectionRoutes, routeEntry, sshTargetKey } from "./routes.ts";
|
||||
|
||||
export interface PairingConnectionInput {
|
||||
readonly pairingUrl?: string;
|
||||
readonly host?: string;
|
||||
readonly pairingCode?: string;
|
||||
/**
|
||||
* Set when adding a route to a saved machine: the pairing must reach this
|
||||
* environment, or nothing is saved.
|
||||
*/
|
||||
readonly expectedEnvironmentId?: EnvironmentId;
|
||||
}
|
||||
|
||||
export interface SshConnectionInput {
|
||||
readonly target: DesktopSshEnvironmentTarget;
|
||||
readonly label?: string;
|
||||
/** Set when adding a route to a saved machine; see `PairingConnectionInput`. */
|
||||
readonly expectedEnvironmentId?: EnvironmentId;
|
||||
}
|
||||
|
||||
export interface BearerConnectionUpdateInput {
|
||||
@@ -84,6 +92,22 @@ const resolvePairingTarget = Effect.fn("clientRuntime.connection.onboarding.reso
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* One bearer route per address, so pairing over Tailscale adds a route next
|
||||
* to the LAN one instead of replacing it. Pairing the same address again
|
||||
* reuses the id and replaces that route.
|
||||
*/
|
||||
function bearerConnectionId(environmentId: EnvironmentId, httpBaseUrl: string): string {
|
||||
return `bearer:${environmentId}:${new URL(httpBaseUrl).origin}`;
|
||||
}
|
||||
|
||||
function differentMachineError(label: string) {
|
||||
return new ConnectionBlockedError({
|
||||
reason: "configuration",
|
||||
detail: `That address reaches ${label}, a different machine. Add it as its own environment instead.`,
|
||||
});
|
||||
}
|
||||
|
||||
export const preparePairingRegistration = Effect.fn(
|
||||
"clientRuntime.connection.onboarding.preparePairingRegistration",
|
||||
)(function* (input: PairingConnectionInput) {
|
||||
@@ -92,6 +116,13 @@ export const preparePairingRegistration = Effect.fn(
|
||||
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: target.httpBaseUrl,
|
||||
}).pipe(Effect.mapError(mapRemoteEnvironmentError));
|
||||
// Checked before redeeming the one-time code, so a wrong link is not spent.
|
||||
if (
|
||||
input.expectedEnvironmentId !== undefined &&
|
||||
descriptor.environmentId !== input.expectedEnvironmentId
|
||||
) {
|
||||
return yield* differentMachineError(descriptor.label);
|
||||
}
|
||||
const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
|
||||
// An outdated server is still saved so it can be updated from this client.
|
||||
if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {
|
||||
@@ -103,7 +134,7 @@ export const preparePairingRegistration = Effect.fn(
|
||||
scopes: presentation.scopes,
|
||||
clientMetadata: presentation.metadata,
|
||||
}).pipe(Effect.mapError(mapRemoteEnvironmentError));
|
||||
const connectionId = `bearer:${descriptor.environmentId}`;
|
||||
const connectionId = bearerConnectionId(descriptor.environmentId, target.httpBaseUrl);
|
||||
|
||||
return new BearerConnectionRegistration({
|
||||
target: new BearerConnectionTarget({
|
||||
@@ -141,7 +172,15 @@ const updateBearerConnection = Effect.fn(
|
||||
)(function* (input: BearerConnectionUpdateInput) {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
|
||||
const entry = (yield* SubscriptionRef.get(registry.entries)).get(input.environmentId);
|
||||
const saved = (yield* SubscriptionRef.get(registry.entries)).get(input.environmentId);
|
||||
// Editing changes the environment's first direct route; others stay as saved.
|
||||
const route =
|
||||
saved === undefined
|
||||
? undefined
|
||||
: connectionRoutes(saved).find(
|
||||
(candidate) => candidate.target._tag === "BearerConnectionTarget",
|
||||
);
|
||||
const entry = saved === undefined || route === undefined ? saved : routeEntry(saved, route);
|
||||
const credential =
|
||||
entry?.target._tag === "BearerConnectionTarget"
|
||||
? yield* credentials.get(entry.target.connectionId)
|
||||
@@ -220,8 +259,10 @@ export const prepareSshRegistration = Effect.fn(
|
||||
"clientRuntime.connection.onboarding.prepareSshRegistration",
|
||||
)(function* (input: SshConnectionInput) {
|
||||
const gateway = yield* ClientCapabilities.SshEnvironmentGateway;
|
||||
const provisioned = yield* gateway.provision(input.target);
|
||||
const connectionId = `ssh:${provisioned.environmentId}`;
|
||||
const provisioned = yield* gateway.provision(input.target, input.expectedEnvironmentId);
|
||||
// One id per SSH target, so a second host or alias for the same machine
|
||||
// adds a route instead of replacing the first.
|
||||
const connectionId = `ssh:${provisioned.environmentId}:${sshTargetKey(provisioned.bootstrap.target)}`;
|
||||
const label = input.label?.trim() || provisioned.label || provisioned.bootstrap.target.alias;
|
||||
|
||||
return new SshConnectionRegistration({
|
||||
@@ -243,6 +284,12 @@ const registerSshConnection = Effect.fn(
|
||||
"clientRuntime.connection.onboarding.registerSshConnection",
|
||||
)(function* (input: SshConnectionInput) {
|
||||
const registration = yield* prepareSshRegistration(input);
|
||||
if (
|
||||
input.expectedEnvironmentId !== undefined &&
|
||||
registration.target.environmentId !== input.expectedEnvironmentId
|
||||
) {
|
||||
return yield* differentMachineError(registration.target.label);
|
||||
}
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
yield* registry.register(registration);
|
||||
return registration.target.environmentId;
|
||||
|
||||
@@ -26,6 +26,7 @@ import { isLegacyUpdateHandoffLoss, resolveServerUpdateProgressResult } from "..
|
||||
import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
|
||||
import * as ConnectionResolver from "./resolver.ts";
|
||||
import * as EnvironmentRegistry from "./registry.ts";
|
||||
import { connectionRoutes, hasRelayRoute, routeEntry, routeHttpBaseUrl } from "./routes.ts";
|
||||
|
||||
// A v1 host restarting into v2 runs migrations before its descriptor answers again.
|
||||
const OUTDATED_HOST_RESTART_TIMEOUT = Duration.minutes(4);
|
||||
@@ -63,7 +64,11 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutd
|
||||
if (entry === undefined) {
|
||||
return yield* new EnvironmentRegistry.EnvironmentNotRegisteredError({ environmentId });
|
||||
}
|
||||
const { prepared, descriptor } = yield* resolver.prepareForUpdate(entry);
|
||||
// An outdated server cannot connect normally, so the routes are tried in
|
||||
// order here. The first that authorizes carries the update.
|
||||
const { prepared, descriptor } = yield* Effect.firstSuccessOf(
|
||||
connectionRoutes(entry).map((route) => resolver.prepareForUpdate(routeEntry(entry, route))),
|
||||
);
|
||||
const capabilities = descriptor.capabilities;
|
||||
if (
|
||||
capabilities.serverSelfUpdate === undefined ||
|
||||
@@ -154,9 +159,23 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutd
|
||||
);
|
||||
|
||||
yield* onStage("resuming");
|
||||
const resumed = yield* fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: prepared.httpBaseUrl,
|
||||
}).pipe(
|
||||
// The restarted host may answer on another saved route, so each poll asks
|
||||
// every direct address, the one that carried the update first.
|
||||
const pollUrls = [
|
||||
prepared.httpBaseUrl,
|
||||
...connectionRoutes(entry).flatMap((route) => routeHttpBaseUrl(route) ?? []),
|
||||
].filter((url, index, all) => all.indexOf(url) === index);
|
||||
const resumed = yield* Effect.firstSuccessOf(
|
||||
pollUrls.map((httpBaseUrl) =>
|
||||
fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
|
||||
Effect.filterOrFail(
|
||||
(descriptor) =>
|
||||
descriptor.environmentId === environmentId && isCompatibleDescriptor(descriptor),
|
||||
() => "not-ready" as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.option,
|
||||
Effect.repeat({
|
||||
@@ -175,7 +194,7 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutd
|
||||
|
||||
// Discovery still holds the old relay descriptor and would re-block the
|
||||
// environment from it, so replace that before clearing the block.
|
||||
if (entry.target._tag === "RelayConnectionTarget") {
|
||||
if (hasRelayRoute(entry)) {
|
||||
const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
|
||||
yield* discovery.refresh;
|
||||
}
|
||||
|
||||
@@ -26,16 +26,21 @@ import {
|
||||
BearerConnectionCredential,
|
||||
BearerConnectionProfile,
|
||||
BearerConnectionRegistration,
|
||||
type ConnectionCatalogEntry,
|
||||
type ConnectionRegistration,
|
||||
type ConnectionRoute,
|
||||
PrimaryConnectionRegistration,
|
||||
RelayConnectionRegistration,
|
||||
SshConnectionProfile,
|
||||
SshConnectionRegistration,
|
||||
type ConnectionCredential,
|
||||
type ConnectionProfile,
|
||||
} from "./catalog.ts";
|
||||
import * as Connectivity from "./connectivity.ts";
|
||||
import * as ConnectionCredentialStore from "./credentialStore.ts";
|
||||
import * as ConnectionDriver from "./driver.ts";
|
||||
import type { RouteCheck } from "./driver.ts";
|
||||
import { connectionRouteId } from "./routes.ts";
|
||||
import {
|
||||
ConnectionTransientError,
|
||||
ConnectionBlockedError,
|
||||
@@ -52,6 +57,7 @@ import * as ConnectionProfileStore from "./profileStore.ts";
|
||||
import * as EnvironmentRegistry from "./registry.ts";
|
||||
import {
|
||||
GitHubRoutingPermissions,
|
||||
type StoredGitHubRoutingPermission,
|
||||
makeGitHubRoutingPermissions,
|
||||
} from "./githubRoutingPermissions.ts";
|
||||
import * as RpcSession from "../rpc/session.ts";
|
||||
@@ -148,14 +154,14 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
|
||||
registration: ConnectionRegistration,
|
||||
) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
|
||||
readonly beforeRegistrationRemove?: (
|
||||
target: ConnectionTarget,
|
||||
environmentId: EnvironmentId,
|
||||
) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
|
||||
readonly checkRoute?: (route: ConnectionRoute) => RouteCheck;
|
||||
readonly prepareRoute?: (target: ConnectionTarget) => ConnectionBlockedError | undefined;
|
||||
readonly initialDisabled?: ReadonlyArray<EnvironmentId>;
|
||||
},
|
||||
) {
|
||||
const storedTargets = yield* Ref.make(
|
||||
new Map(initialTargets.map((target) => [target.environmentId, target])),
|
||||
);
|
||||
const storedTargets = yield* Ref.make<ReadonlyArray<ConnectionTarget>>(initialTargets);
|
||||
const shellCache = yield* Ref.make(new Map([[TARGET.environmentId, CACHED_SNAPSHOT]]));
|
||||
const cacheClears = yield* Ref.make<ReadonlyArray<EnvironmentId>>([]);
|
||||
const ownedDataClears = yield* Ref.make<ReadonlyArray<EnvironmentId>>([]);
|
||||
@@ -191,18 +197,16 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
|
||||
new Set(options?.initialDisabled ?? []),
|
||||
);
|
||||
const targetStore = Persistence.ConnectionTargetStore.of({
|
||||
list: Ref.get(storedTargets).pipe(Effect.map((targets) => [...targets.values()])),
|
||||
list: Ref.get(storedTargets),
|
||||
listDisabled: Ref.get(storedDisabled).pipe(Effect.map((ids) => [...ids])),
|
||||
});
|
||||
const registrationStore = Persistence.ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
register: (registration, routes) =>
|
||||
Effect.gen(function* () {
|
||||
yield* options?.beforeRegistrationRegister?.(registration) ?? Effect.void;
|
||||
yield* Ref.update(storedTargets, (current) => {
|
||||
const next = new Map(current);
|
||||
next.set(registration.target.environmentId, registration.target);
|
||||
return next;
|
||||
});
|
||||
yield* Ref.update(storedTargets, (current) =>
|
||||
replaceRoutes(current, registration.target.environmentId, routes),
|
||||
);
|
||||
switch (registration._tag) {
|
||||
case "RelayConnectionRegistration":
|
||||
return;
|
||||
@@ -226,29 +230,34 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
|
||||
});
|
||||
}
|
||||
}),
|
||||
remove: (target) =>
|
||||
setRoutes: (environmentId, routes) =>
|
||||
Ref.update(storedTargets, (current) => replaceRoutes(current, environmentId, routes)),
|
||||
remove: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
yield* options?.beforeRegistrationRemove?.(target) ?? Effect.void;
|
||||
yield* Ref.update(storedTargets, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(target.environmentId);
|
||||
return next;
|
||||
});
|
||||
if (target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget") {
|
||||
yield* Ref.update(storedProfiles, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(target.connectionId);
|
||||
return next;
|
||||
});
|
||||
yield* Ref.update(storedCredentials, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(target.connectionId);
|
||||
return next;
|
||||
});
|
||||
yield* options?.beforeRegistrationRemove?.(environmentId) ?? Effect.void;
|
||||
const removed = (yield* Ref.get(storedTargets)).filter(
|
||||
(target) => target.environmentId === environmentId,
|
||||
);
|
||||
yield* Ref.update(storedTargets, (current) =>
|
||||
current.filter((target) => target.environmentId !== environmentId),
|
||||
);
|
||||
for (const target of removed) {
|
||||
if (target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget") {
|
||||
yield* Ref.update(storedProfiles, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(target.connectionId);
|
||||
return next;
|
||||
});
|
||||
yield* Ref.update(storedCredentials, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(target.connectionId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* Ref.update(storedRemoteTokens, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(target.environmentId);
|
||||
next.delete(environmentId);
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
@@ -363,38 +372,52 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
|
||||
prepare: () => Effect.die(new Error("SSH preparation is not used.")),
|
||||
disconnect: (target) => Ref.update(disconnectedSshTargets, (current) => [...current, target]),
|
||||
});
|
||||
const connectedRoutes = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const checkRoute = (route: ConnectionRoute) =>
|
||||
Effect.succeed(options?.checkRoute?.(route) ?? "unchecked");
|
||||
const connectRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
|
||||
Effect.gen(function* () {
|
||||
const target = route.target;
|
||||
const prepared = {
|
||||
...PREPARED,
|
||||
environmentId: target.environmentId,
|
||||
label: target.label,
|
||||
target,
|
||||
};
|
||||
if (options?.prepareError) return yield* options.prepareError;
|
||||
const routeError = options?.prepareRoute?.(target);
|
||||
if (routeError !== undefined) return yield* routeError;
|
||||
yield* Ref.update(connectedRoutes, (current) => [...current, connectionRouteId(target)]);
|
||||
yield* options?.beforeSessionConnect?.(target.environmentId) ?? Effect.void;
|
||||
const closed = yield* Deferred.make<never, ConnectionTransientError>();
|
||||
yield* Ref.update(sessions, (current) => [...current, { closed }]);
|
||||
const session = yield* Effect.acquireRelease(
|
||||
Effect.succeed({
|
||||
client: {} as RpcSession.RpcSession["client"],
|
||||
initialConfig: Effect.die(new Error("Config is not used by registry tests.")),
|
||||
subscribeServerConfig: () =>
|
||||
Stream.die(new Error("Config is not used by registry tests.")),
|
||||
ready: Effect.void,
|
||||
probe: Effect.void,
|
||||
closed: Deferred.await(closed),
|
||||
} satisfies RpcSession.RpcSession),
|
||||
() => Ref.update(releasedSessions, (count) => count + 1),
|
||||
);
|
||||
yield* session.ready;
|
||||
return { prepared, session };
|
||||
});
|
||||
const driver = ConnectionDriver.ConnectionDriver.of({
|
||||
connect: (entry, reportProgress) =>
|
||||
Effect.gen(function* () {
|
||||
const target = entry.target;
|
||||
const prepared = {
|
||||
...PREPARED,
|
||||
environmentId: target.environmentId,
|
||||
label: target.label,
|
||||
target,
|
||||
};
|
||||
yield* reportProgress({ stage: "preparing" });
|
||||
if (options?.prepareError) return yield* options.prepareError;
|
||||
yield* reportProgress({ stage: "opening", prepared });
|
||||
yield* options?.beforeSessionConnect?.(target.environmentId) ?? Effect.void;
|
||||
const closed = yield* Deferred.make<never, ConnectionTransientError>();
|
||||
yield* Ref.update(sessions, (current) => [...current, { closed }]);
|
||||
const session = yield* Effect.acquireRelease(
|
||||
Effect.succeed({
|
||||
client: {} as RpcSession.RpcSession["client"],
|
||||
initialConfig: Effect.die(new Error("Config is not used by registry tests.")),
|
||||
subscribeServerConfig: () =>
|
||||
Stream.die(new Error("Config is not used by registry tests.")),
|
||||
ready: Effect.void,
|
||||
probe: Effect.void,
|
||||
closed: Deferred.await(closed),
|
||||
} satisfies RpcSession.RpcSession),
|
||||
() => Ref.update(releasedSessions, (count) => count + 1),
|
||||
);
|
||||
yield* reportProgress({ stage: "synchronizing", prepared });
|
||||
yield* session.ready;
|
||||
return { prepared, session };
|
||||
}),
|
||||
reportProgress({ stage: "preparing" }).pipe(
|
||||
Effect.andThen(
|
||||
ConnectionDriver.connectOverRoutes(entry, checkRoute, (route) =>
|
||||
connectRoute(entry, route),
|
||||
),
|
||||
),
|
||||
),
|
||||
checkRoute: (_entry, route) => checkRoute(route),
|
||||
preflight: (_entry, route) =>
|
||||
checkRoute(route).pipe(Effect.map((check) => check === "answered")),
|
||||
});
|
||||
|
||||
const cacheLayer = Layer.succeed(Persistence.EnvironmentCacheStore, cacheStore);
|
||||
@@ -434,9 +457,33 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
|
||||
storedDisabled,
|
||||
disconnectedSshTargets,
|
||||
networkStatus,
|
||||
connectedRoutes,
|
||||
};
|
||||
});
|
||||
|
||||
function routesOf(targets: ReadonlyArray<ConnectionTarget>, environmentId: EnvironmentId) {
|
||||
return targets.filter((target) => target.environmentId === environmentId);
|
||||
}
|
||||
|
||||
function hasRoutes(targets: ReadonlyArray<ConnectionTarget>, environmentId: EnvironmentId) {
|
||||
return routesOf(targets, environmentId).length > 0;
|
||||
}
|
||||
|
||||
function replaceRoutes(
|
||||
current: ReadonlyArray<ConnectionTarget>,
|
||||
environmentId: EnvironmentId,
|
||||
routes: ReadonlyArray<ConnectionTarget>,
|
||||
): ReadonlyArray<ConnectionTarget> {
|
||||
const firstIndex = current.findIndex((target) => target.environmentId === environmentId);
|
||||
const others = current.filter((target) => target.environmentId !== environmentId);
|
||||
const insertAt =
|
||||
firstIndex === -1
|
||||
? others.length
|
||||
: current.slice(0, firstIndex).filter((target) => target.environmentId !== environmentId)
|
||||
.length;
|
||||
return [...others.slice(0, insertAt), ...routes, ...others.slice(insertAt)];
|
||||
}
|
||||
|
||||
function awaitConnectionState(
|
||||
registry: EnvironmentRegistry.EnvironmentRegistry["Service"],
|
||||
environmentId: EnvironmentId,
|
||||
@@ -649,7 +696,7 @@ describe("EnvironmentRegistry", () => {
|
||||
);
|
||||
|
||||
yield* registry.remove(TARGET.environmentId);
|
||||
expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
|
||||
expect(hasRoutes(yield* Ref.get(harness.storedTargets), TARGET.environmentId)).toBe(false);
|
||||
expect((yield* Ref.get(harness.shellCache)).has(TARGET.environmentId)).toBe(false);
|
||||
expect(yield* Ref.get(harness.cacheClears)).toEqual([TARGET.environmentId]);
|
||||
expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe(
|
||||
@@ -672,8 +719,8 @@ describe("EnvironmentRegistry", () => {
|
||||
(state) => state.phase === "connected",
|
||||
);
|
||||
|
||||
expect((yield* Ref.get(harness.storedTargets)).get(RELAY_TARGET.environmentId)).toEqual(
|
||||
RELAY_TARGET,
|
||||
expect(routesOf(yield* Ref.get(harness.storedTargets), RELAY_TARGET.environmentId)).toEqual(
|
||||
[RELAY_TARGET],
|
||||
);
|
||||
expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
|
||||
}).pipe(Effect.provide(harness.layer));
|
||||
@@ -997,7 +1044,9 @@ describe("EnvironmentRegistry", () => {
|
||||
);
|
||||
expect(entry?.enabled).toBe(false);
|
||||
expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(true);
|
||||
expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
|
||||
expect(hasRoutes(yield* Ref.get(harness.storedTargets), RELAY_TARGET.environmentId)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(yield* Ref.get(harness.releasedSessions)).toBe(1);
|
||||
|
||||
yield* registry.setEnabled(RELAY_TARGET.environmentId, true);
|
||||
@@ -1060,7 +1109,7 @@ describe("EnvironmentRegistry", () => {
|
||||
);
|
||||
|
||||
expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);
|
||||
expect((yield* Ref.get(harness.storedTargets)).has(SSH_CONNECTION.environmentId)).toBe(
|
||||
expect(hasRoutes(yield* Ref.get(harness.storedTargets), SSH_CONNECTION.environmentId)).toBe(
|
||||
true,
|
||||
);
|
||||
}).pipe(Effect.provide(harness.layer));
|
||||
@@ -1168,9 +1217,9 @@ describe("EnvironmentRegistry", () => {
|
||||
yield* registry.removeRelayEnvironments();
|
||||
|
||||
const targets = yield* Ref.get(harness.storedTargets);
|
||||
expect(targets.has(RELAY_TARGET.environmentId)).toBe(false);
|
||||
expect(targets.has(SECOND_RELAY_TARGET.environmentId)).toBe(false);
|
||||
expect(targets.get(BEARER_TARGET.environmentId)).toEqual(BEARER_TARGET);
|
||||
expect(hasRoutes(targets, RELAY_TARGET.environmentId)).toBe(false);
|
||||
expect(hasRoutes(targets, SECOND_RELAY_TARGET.environmentId)).toBe(false);
|
||||
expect(routesOf(targets, BEARER_TARGET.environmentId)).toEqual([BEARER_TARGET]);
|
||||
expect(yield* Ref.get(harness.cacheClears)).toEqual(
|
||||
expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
|
||||
);
|
||||
@@ -1212,7 +1261,9 @@ describe("EnvironmentRegistry", () => {
|
||||
expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(
|
||||
true,
|
||||
);
|
||||
expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
|
||||
expect(hasRoutes(yield* Ref.get(harness.storedTargets), RELAY_TARGET.environmentId)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(yield* Ref.get(harness.cacheClears)).toEqual([]);
|
||||
expect(yield* Ref.get(harness.ownedDataClears)).toEqual([]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
@@ -1262,7 +1313,7 @@ describe("EnvironmentRegistry", () => {
|
||||
(state) => state.phase === "connected",
|
||||
);
|
||||
|
||||
expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
|
||||
expect(hasRoutes(yield* Ref.get(harness.storedTargets), TARGET.environmentId)).toBe(false);
|
||||
expect(
|
||||
(yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
|
||||
).toEqual(TARGET);
|
||||
@@ -1298,14 +1349,14 @@ describe("EnvironmentRegistry", () => {
|
||||
expect(
|
||||
(yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
|
||||
).toEqual(TARGET);
|
||||
expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
|
||||
expect(hasRoutes(yield* Ref.get(harness.storedTargets), TARGET.environmentId)).toBe(false);
|
||||
|
||||
yield* registry.register(new RelayConnectionRegistration({ target: shadowedTarget }));
|
||||
|
||||
expect(
|
||||
(yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
|
||||
).toEqual(TARGET);
|
||||
expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
|
||||
expect(hasRoutes(yield* Ref.get(harness.storedTargets), TARGET.environmentId)).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(harness.layer),
|
||||
Effect.provideService(GitHubRoutingPermissions, permissions),
|
||||
@@ -1582,3 +1633,245 @@ describe("EnvironmentRegistry", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("EnvironmentRegistry routes", () => {
|
||||
// The relay environment, reachable on the LAN as well.
|
||||
const LAN_TARGET = new BearerConnectionTarget({
|
||||
environmentId: RELAY_TARGET.environmentId,
|
||||
label: RELAY_TARGET.label,
|
||||
connectionId: "bearer:lan",
|
||||
});
|
||||
const LAN_PROFILE = new BearerConnectionProfile({
|
||||
connectionId: LAN_TARGET.connectionId,
|
||||
environmentId: LAN_TARGET.environmentId,
|
||||
label: LAN_TARGET.label,
|
||||
httpBaseUrl: "http://192.168.1.10:3773/",
|
||||
wsBaseUrl: "ws://192.168.1.10:3773/",
|
||||
});
|
||||
const lanRegistration = (target = LAN_TARGET, profile = LAN_PROFILE) =>
|
||||
new BearerConnectionRegistration({ target, profile, credential: BEARER_CREDENTIAL });
|
||||
|
||||
it.effect("adds a paired LAN route ahead of T3 Connect instead of replacing it", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness([RELAY_TARGET]);
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
yield* registry.register(lanRegistration());
|
||||
|
||||
expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([
|
||||
LAN_TARGET,
|
||||
RELAY_TARGET,
|
||||
]);
|
||||
const entry = (yield* SubscriptionRef.get(registry.entries)).get(LAN_TARGET.environmentId);
|
||||
expect(entry?.target).toEqual(LAN_TARGET);
|
||||
expect(entry?.alternateRoutes?.map((route) => route.target)).toEqual([RELAY_TARGET]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-pairing the same address replaces that route rather than adding another", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness(
|
||||
[LAN_TARGET, RELAY_TARGET],
|
||||
[LAN_PROFILE],
|
||||
[[LAN_TARGET.connectionId, BEARER_CREDENTIAL]],
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
const repaired = new BearerConnectionTarget({
|
||||
...LAN_TARGET,
|
||||
connectionId: "bearer:lan-again",
|
||||
});
|
||||
yield* registry.register(
|
||||
lanRegistration(
|
||||
repaired,
|
||||
new BearerConnectionProfile({ ...LAN_PROFILE, connectionId: repaired.connectionId }),
|
||||
),
|
||||
);
|
||||
|
||||
expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([
|
||||
repaired,
|
||||
RELAY_TARGET,
|
||||
]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("a second SSH host for the same machine adds a route beside the first", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
const other = new SshConnectionTarget({
|
||||
...SSH_CONNECTION,
|
||||
connectionId: "ssh-connection-other-host",
|
||||
});
|
||||
yield* registry.register(
|
||||
new SshConnectionRegistration({
|
||||
target: other,
|
||||
profile: new SshConnectionProfile({
|
||||
...SSH_PROFILE,
|
||||
connectionId: other.connectionId,
|
||||
target: { ...SSH_TARGET, alias: "other", hostname: "other.example.test" },
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
routesOf(yield* Ref.get(harness.storedTargets), SSH_CONNECTION.environmentId),
|
||||
).toEqual([SSH_CONNECTION, other]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"adding a saved SSH host again replaces its route, whatever id it was saved under",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
const again = new SshConnectionTarget({
|
||||
...SSH_CONNECTION,
|
||||
connectionId: "ssh-connection-new-id",
|
||||
});
|
||||
yield* registry.register(
|
||||
new SshConnectionRegistration({
|
||||
target: again,
|
||||
profile: new SshConnectionProfile({
|
||||
...SSH_PROFILE,
|
||||
connectionId: again.connectionId,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
routesOf(yield* Ref.get(harness.storedTargets), SSH_CONNECTION.environmentId),
|
||||
).toEqual([again]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("signing out of T3 Connect keeps an environment that still has a LAN route", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness(
|
||||
[LAN_TARGET, RELAY_TARGET, SECOND_RELAY_TARGET],
|
||||
[LAN_PROFILE],
|
||||
[[LAN_TARGET.connectionId, BEARER_CREDENTIAL]],
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
yield* registry.removeRelayEnvironments();
|
||||
|
||||
const targets = yield* Ref.get(harness.storedTargets);
|
||||
expect(routesOf(targets, LAN_TARGET.environmentId)).toEqual([LAN_TARGET]);
|
||||
expect(hasRoutes(targets, SECOND_RELAY_TARGET.environmentId)).toBe(false);
|
||||
// Only the environment that lost its last route is forgotten.
|
||||
expect(yield* Ref.get(harness.cacheClears)).toEqual([SECOND_RELAY_TARGET.environmentId]);
|
||||
expect(
|
||||
(yield* SubscriptionRef.get(registry.entries)).get(LAN_TARGET.environmentId)?.target,
|
||||
).toEqual(LAN_TARGET);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reorders routes and rejects an order that drops one", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness(
|
||||
[LAN_TARGET, RELAY_TARGET],
|
||||
[LAN_PROFILE],
|
||||
[[LAN_TARGET.connectionId, BEARER_CREDENTIAL]],
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
yield* registry.reorderRoutes(LAN_TARGET.environmentId, ["relay", LAN_TARGET.connectionId]);
|
||||
expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([
|
||||
RELAY_TARGET,
|
||||
LAN_TARGET,
|
||||
]);
|
||||
|
||||
const error = yield* registry
|
||||
.reorderRoutes(LAN_TARGET.environmentId, ["relay"])
|
||||
.pipe(Effect.flip);
|
||||
expect(error._tag).toBe("ConnectionBlockedError");
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("removing the last route forgets the environment", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness(
|
||||
[LAN_TARGET, RELAY_TARGET],
|
||||
[LAN_PROFILE],
|
||||
[[LAN_TARGET.connectionId, BEARER_CREDENTIAL]],
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
yield* registry.removeRoute(LAN_TARGET.environmentId, LAN_TARGET.connectionId);
|
||||
expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([
|
||||
RELAY_TARGET,
|
||||
]);
|
||||
expect(yield* Ref.get(harness.cacheClears)).toEqual([]);
|
||||
|
||||
yield* registry.removeRoute(LAN_TARGET.environmentId, "relay");
|
||||
expect(hasRoutes(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(yield* Ref.get(harness.cacheClears)).toEqual([LAN_TARGET.environmentId]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("revokes GitHub routing trust when a route is added but keeps it on reorder", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness([RELAY_TARGET]);
|
||||
let stored: ReadonlyArray<StoredGitHubRoutingPermission> = [];
|
||||
const permissions = yield* makeGitHubRoutingPermissions({
|
||||
read: Effect.sync(() => stored),
|
||||
write: (next) => Effect.sync(() => void (stored = next)),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
const current = () =>
|
||||
SubscriptionRef.get(registry.entries).pipe(
|
||||
Effect.map((entries) => entries.get(RELAY_TARGET.environmentId)!),
|
||||
);
|
||||
yield* permissions.set(yield* current(), "read");
|
||||
yield* registry.register(lanRegistration());
|
||||
expect(yield* permissions.get(yield* current())).toBe("off");
|
||||
|
||||
yield* permissions.set(yield* current(), "read");
|
||||
yield* registry.reorderRoutes(LAN_TARGET.environmentId, ["relay", LAN_TARGET.connectionId]);
|
||||
expect(yield* permissions.get(yield* current())).toBe("read");
|
||||
}).pipe(
|
||||
Effect.provide(harness.layer),
|
||||
Effect.provideService(GitHubRoutingPermissions, permissions),
|
||||
Effect.scoped,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("loads saved routes grouped by environment, in saved order", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness(
|
||||
[LAN_TARGET, BEARER_TARGET, RELAY_TARGET],
|
||||
[LAN_PROFILE, BEARER_PROFILE],
|
||||
[
|
||||
[LAN_TARGET.connectionId, BEARER_CREDENTIAL],
|
||||
[BEARER_TARGET.connectionId, BEARER_CREDENTIAL],
|
||||
],
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
|
||||
const entries = yield* SubscriptionRef.get(registry.entries);
|
||||
expect([...entries.keys()]).toEqual([
|
||||
LAN_TARGET.environmentId,
|
||||
BEARER_TARGET.environmentId,
|
||||
]);
|
||||
expect(entries.get(LAN_TARGET.environmentId)?.alternateRoutes?.[0]?.target).toEqual(
|
||||
RELAY_TARGET,
|
||||
);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -15,7 +15,9 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
import * as ClientCapabilities from "../platform/capabilities.ts";
|
||||
import {
|
||||
type ConnectionCatalogEntry,
|
||||
type ConnectionProfile,
|
||||
type ConnectionRegistration,
|
||||
type ConnectionRoute,
|
||||
type PlatformConnectionRegistration,
|
||||
type PrimaryConnectionRegistration,
|
||||
SshConnectionProfile,
|
||||
@@ -28,6 +30,7 @@ import type {
|
||||
ConnectionAttemptError,
|
||||
ConnectionTarget,
|
||||
NetworkStatus,
|
||||
PersistedConnectionTarget,
|
||||
SupervisorConnectionState,
|
||||
} from "./model.ts";
|
||||
import { ConnectionBlockedError } from "./model.ts";
|
||||
@@ -39,6 +42,14 @@ import {
|
||||
GitHubRoutingPermissions,
|
||||
gitHubRoutingConnectionKey,
|
||||
} from "./githubRoutingPermissions.ts";
|
||||
import {
|
||||
RELAY_ROUTE_ID,
|
||||
connectionRouteId,
|
||||
connectionRoutes,
|
||||
entryWithRoutes,
|
||||
findRouteToSameAddress,
|
||||
upsertRoute,
|
||||
} from "./routes.ts";
|
||||
|
||||
const isSshConnectionProfile = Schema.is(SshConnectionProfile);
|
||||
|
||||
@@ -99,6 +110,35 @@ export class EnvironmentRegistry extends Context.Service<
|
||||
| EnvironmentNotRegisteredError
|
||||
| PlatformEnvironmentRemovalError
|
||||
>;
|
||||
/**
|
||||
* Drops one route. Removing an environment's last route removes the
|
||||
* environment, the same as `remove`.
|
||||
*/
|
||||
readonly removeRoute: (
|
||||
environmentId: EnvironmentId,
|
||||
routeId: string,
|
||||
) => Effect.Effect<
|
||||
void,
|
||||
| Persistence.ConnectionPersistenceError
|
||||
| ConnectionAttemptError
|
||||
| EnvironmentNotRegisteredError
|
||||
| PlatformEnvironmentRemovalError
|
||||
>;
|
||||
/** Reorders an environment's routes; `routeIds` lists every route, preferred first. */
|
||||
readonly reorderRoutes: (
|
||||
environmentId: EnvironmentId,
|
||||
routeIds: ReadonlyArray<string>,
|
||||
) => Effect.Effect<
|
||||
void,
|
||||
| Persistence.ConnectionPersistenceError
|
||||
| EnvironmentNotRegisteredError
|
||||
| PlatformEnvironmentRemovalError
|
||||
| ConnectionBlockedError
|
||||
>;
|
||||
/**
|
||||
* Drops the T3 Connect route of every environment, after a cloud sign-out
|
||||
* or account change. Environments with no other route are removed.
|
||||
*/
|
||||
readonly removeRelayEnvironments: () => Effect.Effect<
|
||||
void,
|
||||
| Persistence.ConnectionPersistenceError
|
||||
@@ -175,21 +215,37 @@ export const make = Effect.gen(function* () {
|
||||
const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
|
||||
const persistedTargets = yield* storage.list;
|
||||
const disabledEnvironmentIds = new Set(yield* storage.listDisabled);
|
||||
const loadRoute = Effect.fn("EnvironmentRegistry.loadRoute")(function* (
|
||||
target: ConnectionTarget,
|
||||
) {
|
||||
const profile: Option.Option<ConnectionProfile> =
|
||||
target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget"
|
||||
? yield* profiles.get(target.connectionId)
|
||||
: Option.none();
|
||||
return { target, profile } satisfies ConnectionRoute;
|
||||
});
|
||||
const persistedRoutesByEnvironment = new Map<EnvironmentId, Array<ConnectionTarget>>();
|
||||
for (const target of persistedTargets) {
|
||||
const routes = persistedRoutesByEnvironment.get(target.environmentId) ?? [];
|
||||
routes.push(target);
|
||||
persistedRoutesByEnvironment.set(target.environmentId, routes);
|
||||
}
|
||||
const initialEntries = new Map(
|
||||
yield* Effect.forEach(
|
||||
persistedTargets,
|
||||
Effect.fn("EnvironmentRegistry.loadCatalogEntry")(function* (target) {
|
||||
const profile =
|
||||
target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget"
|
||||
? yield* profiles.get(target.connectionId)
|
||||
: Option.none();
|
||||
persistedRoutesByEnvironment,
|
||||
Effect.fn("EnvironmentRegistry.loadCatalogEntry")(function* ([environmentId, targets]) {
|
||||
const routes = yield* Effect.forEach(targets, loadRoute, { concurrency: "unbounded" });
|
||||
const first = routes[0]!;
|
||||
return [
|
||||
target.environmentId,
|
||||
{
|
||||
target,
|
||||
profile,
|
||||
enabled: !disabledEnvironmentIds.has(target.environmentId),
|
||||
} satisfies ConnectionCatalogEntry,
|
||||
environmentId,
|
||||
entryWithRoutes(
|
||||
{
|
||||
target: first.target,
|
||||
profile: first.profile,
|
||||
enabled: !disabledEnvironmentIds.has(environmentId),
|
||||
},
|
||||
routes,
|
||||
),
|
||||
] as const;
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
@@ -202,9 +258,9 @@ export const make = Effect.gen(function* () {
|
||||
ReadonlyMap<EnvironmentId, EnvironmentServiceScope>
|
||||
>(new Map());
|
||||
const platformEnvironmentIds = yield* Ref.make<ReadonlySet<EnvironmentId>>(new Set());
|
||||
const persistedTargetsByEnvironment = yield* Ref.make<
|
||||
ReadonlyMap<EnvironmentId, ConnectionTarget>
|
||||
>(new Map(persistedTargets.map((target) => [target.environmentId, target])));
|
||||
const persistedEnvironmentIds = yield* Ref.make<ReadonlySet<EnvironmentId>>(
|
||||
new Set(persistedRoutesByEnvironment.keys()),
|
||||
);
|
||||
interface LeaseLock {
|
||||
readonly semaphore: Semaphore.Semaphore;
|
||||
readonly users: number;
|
||||
@@ -407,9 +463,9 @@ export const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
yield* Effect.forEach(
|
||||
persistedTargets,
|
||||
(target) =>
|
||||
acquireSupervisor(target.environmentId).pipe(
|
||||
persistedRoutesByEnvironment.keys(),
|
||||
(environmentId) =>
|
||||
acquireSupervisor(environmentId).pipe(
|
||||
Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
|
||||
),
|
||||
{
|
||||
@@ -445,6 +501,38 @@ export const make = Effect.gen(function* () {
|
||||
yield* createServiceScope(entry);
|
||||
});
|
||||
|
||||
const forgetRoutingTrust = (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "register-connection" | "set-connection-routes",
|
||||
) =>
|
||||
githubRoutingPermissions.forget(environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new Persistence.ConnectionPersistenceError({
|
||||
operation,
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const persistedRoutes = (entry: ConnectionCatalogEntry) =>
|
||||
connectionRoutes(entry).map((route) => route.target as PersistedConnectionTarget);
|
||||
|
||||
/**
|
||||
* The entry after its routes change. GitHub trust and an unsupported
|
||||
* verdict both belong to the saved addresses: a changed set may reach a
|
||||
* different server, so both are dropped and the next connection decides.
|
||||
* Reordering keeps the same addresses, so both stay.
|
||||
*/
|
||||
const withRoutes = (previous: ConnectionCatalogEntry, routes: ReadonlyArray<ConnectionRoute>) => {
|
||||
const next = entryWithRoutes(previous, routes);
|
||||
if (gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(next)) {
|
||||
return { entry: next, addressesChanged: false };
|
||||
}
|
||||
const { unsupportedReason: _reason, serverUpdateRequired: _update, ...rest } = next;
|
||||
return { entry: rest, addressesChanged: true };
|
||||
};
|
||||
|
||||
const register = Effect.fn("EnvironmentRegistry.register")(function* (
|
||||
registration: ConnectionRegistration,
|
||||
) {
|
||||
@@ -456,44 +544,58 @@ export const make = Effect.gen(function* () {
|
||||
if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
|
||||
return;
|
||||
}
|
||||
// Editing a saved environment must preserve its disabled state.
|
||||
// A new route joins the environment's saved routes. Registering one it
|
||||
// already has (the same id, or a pairing to the same address) replaces
|
||||
// it in place. Editing keeps the disabled state.
|
||||
const previous = (yield* SubscriptionRef.get(entries)).get(environmentId);
|
||||
const entry: ConnectionCatalogEntry =
|
||||
previous === undefined
|
||||
? registered
|
||||
: {
|
||||
...registered,
|
||||
enabled: previous.enabled,
|
||||
...(previous.unsupportedReason !== undefined &&
|
||||
gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(registered)
|
||||
? unsupportedState(previous)
|
||||
: {}),
|
||||
};
|
||||
if (
|
||||
previous !== undefined &&
|
||||
gitHubRoutingConnectionKey(previous) !== gitHubRoutingConnectionKey(entry)
|
||||
) {
|
||||
yield* githubRoutingPermissions.forget(environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new Persistence.ConnectionPersistenceError({
|
||||
operation: "register-connection",
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
let entry = registered;
|
||||
if (previous !== undefined) {
|
||||
const route: ConnectionRoute = { target: registered.target, profile: registered.profile };
|
||||
const existing = connectionRoutes(previous);
|
||||
const sameAddress = findRouteToSameAddress(existing, route);
|
||||
const routes = existing.filter(
|
||||
(existing) =>
|
||||
existing !== sameAddress ||
|
||||
connectionRouteId(existing.target) === connectionRouteId(route.target),
|
||||
);
|
||||
const next = withRoutes(previous, upsertRoute(routes, route));
|
||||
if (next.addressesChanged) {
|
||||
yield* forgetRoutingTrust(environmentId, "register-connection");
|
||||
}
|
||||
entry = next.entry;
|
||||
}
|
||||
yield* registrations.register(registration);
|
||||
yield* Ref.update(persistedTargetsByEnvironment, (current) => {
|
||||
const next = new Map(current);
|
||||
next.set(environmentId, registration.target);
|
||||
return next;
|
||||
});
|
||||
yield* registrations.register(registration, persistedRoutes(entry));
|
||||
yield* Ref.update(persistedEnvironmentIds, (current) =>
|
||||
new Set(current).add(environmentId),
|
||||
);
|
||||
yield* installEntryLocked(entry);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
/** Writes a new route list for a user-saved environment and restarts its connection. */
|
||||
const replaceRoutesLocked = Effect.fn("EnvironmentRegistry.replaceRoutesLocked")(function* (
|
||||
previous: ConnectionCatalogEntry,
|
||||
routes: ReadonlyArray<ConnectionRoute>,
|
||||
) {
|
||||
const environmentId = previous.target.environmentId;
|
||||
const next = withRoutes(previous, routes);
|
||||
if (next.addressesChanged) {
|
||||
yield* forgetRoutingTrust(environmentId, "set-connection-routes");
|
||||
}
|
||||
yield* registrations.setRoutes(environmentId, persistedRoutes(next.entry));
|
||||
yield* installEntryLocked(next.entry);
|
||||
});
|
||||
|
||||
const userEntry = Effect.fn("EnvironmentRegistry.userEntry")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
) {
|
||||
if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
|
||||
return yield* new PlatformEnvironmentRemovalError({ environmentId });
|
||||
}
|
||||
return yield* getEntry(environmentId);
|
||||
});
|
||||
|
||||
const installPlatformRegistration = Effect.fn("EnvironmentRegistry.installPlatformRegistration")(
|
||||
function* (registration: PlatformConnectionRegistration) {
|
||||
const registered = connectionRegistrationCatalogEntry(registration);
|
||||
@@ -507,11 +609,9 @@ export const make = Effect.gen(function* () {
|
||||
gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(registered)
|
||||
? { ...registered, enabled: false, ...unsupportedState(previous) }
|
||||
: registered;
|
||||
const persistedTarget = (yield* Ref.get(persistedTargetsByEnvironment)).get(
|
||||
target.environmentId,
|
||||
);
|
||||
const persisted = (yield* Ref.get(persistedEnvironmentIds)).has(target.environmentId);
|
||||
if (
|
||||
persistedTarget !== undefined ||
|
||||
persisted ||
|
||||
(previous !== undefined &&
|
||||
gitHubRoutingConnectionKey(previous) !== gitHubRoutingConnectionKey(entry))
|
||||
) {
|
||||
@@ -550,11 +650,11 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
if (persistedTarget !== undefined) {
|
||||
yield* registrations.remove(persistedTarget).pipe(
|
||||
if (persisted) {
|
||||
yield* registrations.remove(target.environmentId).pipe(
|
||||
Effect.tap(() =>
|
||||
Ref.update(persistedTargetsByEnvironment, (current) => {
|
||||
const next = new Map(current);
|
||||
Ref.update(persistedEnvironmentIds, (current) => {
|
||||
const next = new Set(current);
|
||||
next.delete(target.environmentId);
|
||||
return next;
|
||||
}),
|
||||
@@ -665,64 +765,111 @@ export const make = Effect.gen(function* () {
|
||||
yield* Effect.forEach(platformRegistrations, installPlatformRegistration, { discard: true });
|
||||
});
|
||||
|
||||
/** Forgets a user-saved environment. Callers hold its lease lock. */
|
||||
const removeLocked = Effect.fn("EnvironmentRegistry.removeLocked")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
) {
|
||||
if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
|
||||
return yield* new PlatformEnvironmentRemovalError({
|
||||
environmentId,
|
||||
});
|
||||
}
|
||||
const entry = yield* getEntry(environmentId);
|
||||
|
||||
yield* githubRoutingPermissions.forget(environmentId);
|
||||
yield* registrations.remove(environmentId);
|
||||
yield* Ref.update(persistedEnvironmentIds, (current) => {
|
||||
const next = new Set(current);
|
||||
next.delete(environmentId);
|
||||
return next;
|
||||
});
|
||||
yield* closeServiceScope(environmentId);
|
||||
yield* SubscriptionRef.update(entries, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(environmentId);
|
||||
return next;
|
||||
});
|
||||
yield* Effect.all(
|
||||
[
|
||||
cache.clear(environmentId).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear cached environment data after removal.", {
|
||||
environmentId,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
ownedDataCleanup.clear(environmentId),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
|
||||
for (const route of connectionRoutes(entry)) {
|
||||
const profile = Option.getOrNull(route.profile);
|
||||
if (profile !== null && isSshConnectionProfile(profile)) {
|
||||
yield* disconnectSsh(environmentId, profile);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const remove = Effect.fn("EnvironmentRegistry.remove")(function* (environmentId: EnvironmentId) {
|
||||
return yield* withLeaseLock(
|
||||
return yield* withLeaseLock(environmentId, removeLocked(environmentId));
|
||||
});
|
||||
|
||||
const disconnectSsh = (environmentId: EnvironmentId, profile: SshConnectionProfile) =>
|
||||
ssh.disconnect(profile.target).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("Could not disconnect the managed SSH environment.", {
|
||||
environmentId,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
const removeRoute = Effect.fn("EnvironmentRegistry.removeRoute")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
routeId: string,
|
||||
) {
|
||||
// One lock for the whole decision: a route registered between "this was
|
||||
// the last route" and the removal must not be deleted with it.
|
||||
yield* withLeaseLock(
|
||||
environmentId,
|
||||
Effect.gen(function* () {
|
||||
if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
|
||||
return yield* new PlatformEnvironmentRemovalError({
|
||||
environmentId,
|
||||
const entry = yield* userEntry(environmentId);
|
||||
const routes = connectionRoutes(entry);
|
||||
const route = routes.find((candidate) => connectionRouteId(candidate.target) === routeId);
|
||||
if (route === undefined) return;
|
||||
const remaining = routes.filter((candidate) => candidate !== route);
|
||||
if (remaining.length === 0) return yield* removeLocked(environmentId);
|
||||
yield* replaceRoutesLocked(entry, remaining);
|
||||
const profile = Option.getOrNull(route.profile);
|
||||
if (profile !== null && isSshConnectionProfile(profile)) {
|
||||
yield* disconnectSsh(environmentId, profile);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const reorderRoutes = Effect.fn("EnvironmentRegistry.reorderRoutes")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
routeIds: ReadonlyArray<string>,
|
||||
) {
|
||||
yield* withLeaseLock(
|
||||
environmentId,
|
||||
Effect.gen(function* () {
|
||||
const entry = yield* userEntry(environmentId);
|
||||
const routes = connectionRoutes(entry);
|
||||
const byId = new Map(routes.map((route) => [connectionRouteId(route.target), route]));
|
||||
const reordered = routeIds.flatMap((id) => byId.get(id) ?? []);
|
||||
if (reordered.length !== routes.length || new Set(routeIds).size !== routes.length) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "configuration",
|
||||
detail: "The route order must list every saved route once.",
|
||||
});
|
||||
}
|
||||
const target = (yield* getEntry(environmentId)).target;
|
||||
const profile =
|
||||
target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget"
|
||||
? yield* profiles.get(target.connectionId)
|
||||
: Option.none();
|
||||
|
||||
yield* githubRoutingPermissions.forget(environmentId);
|
||||
yield* registrations.remove(target);
|
||||
yield* Ref.update(persistedTargetsByEnvironment, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(environmentId);
|
||||
return next;
|
||||
});
|
||||
yield* closeServiceScope(environmentId);
|
||||
yield* SubscriptionRef.update(entries, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(environmentId);
|
||||
return next;
|
||||
});
|
||||
yield* Effect.all(
|
||||
[
|
||||
cache.clear(environmentId).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear cached environment data after removal.", {
|
||||
environmentId,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
ownedDataCleanup.clear(environmentId),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
|
||||
if (
|
||||
target._tag === "SshConnectionTarget" &&
|
||||
Option.isSome(profile) &&
|
||||
isSshConnectionProfile(profile.value)
|
||||
) {
|
||||
yield* ssh.disconnect(profile.value.target).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("Could not disconnect the managed SSH environment.", {
|
||||
environmentId,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
if (reordered.every((route, index) => route === routes[index])) return;
|
||||
yield* replaceRoutesLocked(entry, reordered);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -730,13 +877,15 @@ export const make = Effect.gen(function* () {
|
||||
const removeRelayEnvironments = Effect.fn("EnvironmentRegistry.removeRelayEnvironments")(
|
||||
function* () {
|
||||
const relayEnvironmentIds = [...(yield* SubscriptionRef.get(entries)).values()]
|
||||
.filter((entry) => entry.target._tag === "RelayConnectionTarget")
|
||||
.filter((entry) =>
|
||||
connectionRoutes(entry).some((route) => route.target._tag === "RelayConnectionTarget"),
|
||||
)
|
||||
.map((entry) => entry.target.environmentId);
|
||||
|
||||
yield* Effect.forEach(
|
||||
relayEnvironmentIds,
|
||||
(environmentId) =>
|
||||
remove(environmentId).pipe(
|
||||
removeRoute(environmentId, RELAY_ROUTE_ID).pipe(
|
||||
Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
|
||||
),
|
||||
{
|
||||
@@ -798,21 +947,13 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
// The supervisor only owns the RPC session. A managed SSH backend and
|
||||
// its tunnel outlive it, so switching off tears those down as well.
|
||||
if (
|
||||
!enabled &&
|
||||
entry.target._tag === "SshConnectionTarget" &&
|
||||
Option.isSome(entry.profile) &&
|
||||
isSshConnectionProfile(entry.profile.value)
|
||||
) {
|
||||
yield* ssh.disconnect(entry.profile.value.target).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("Could not disconnect the switched-off SSH environment.", {
|
||||
environmentId,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
if (!enabled) {
|
||||
for (const route of connectionRoutes(entry)) {
|
||||
const profile = Option.getOrNull(route.profile);
|
||||
if (profile !== null && isSshConnectionProfile(profile)) {
|
||||
yield* disconnectSsh(environmentId, profile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -904,6 +1045,8 @@ export const make = Effect.gen(function* () {
|
||||
registerPlatform,
|
||||
reconcilePlatform,
|
||||
remove,
|
||||
removeRoute,
|
||||
reorderRoutes,
|
||||
removeRelayEnvironments,
|
||||
retryNow,
|
||||
setEnabled,
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { BearerConnectionProfile, type ConnectionRoute } from "./catalog.ts";
|
||||
import { BearerConnectionTarget, RelayConnectionTarget } from "./model.ts";
|
||||
import { connectionRouteKind, connectionRouteLabel, insertRoute, upsertRoute } from "./routes.ts";
|
||||
|
||||
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
|
||||
|
||||
function direct(id: string, httpBaseUrl: string): ConnectionRoute {
|
||||
return {
|
||||
target: new BearerConnectionTarget({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
label: "Desk",
|
||||
connectionId: id,
|
||||
}),
|
||||
profile: Option.some(
|
||||
new BearerConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
label: "Desk",
|
||||
httpBaseUrl,
|
||||
wsBaseUrl: httpBaseUrl.replace(/^http/, "ws"),
|
||||
}),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
const RELAY: ConnectionRoute = {
|
||||
target: new RelayConnectionTarget({ environmentId: ENVIRONMENT_ID, label: "Desk" }),
|
||||
profile: Option.none(),
|
||||
};
|
||||
const LAN = direct("lan", "http://192.168.1.10:3773/");
|
||||
const TAILNET = direct("tailnet", "https://desk.tail1234.ts.net/");
|
||||
const PUBLIC = direct("public", "https://desk.example.com/");
|
||||
|
||||
describe("connection routes", () => {
|
||||
it("classifies direct routes by address", () => {
|
||||
expect(connectionRouteKind(LAN)).toBe("lan");
|
||||
expect(connectionRouteKind(direct("ip", "http://100.101.102.103:3773/"))).toBe("tailnet");
|
||||
expect(connectionRouteKind(TAILNET)).toBe("tailnet");
|
||||
expect(connectionRouteKind(PUBLIC)).toBe("public");
|
||||
expect(connectionRouteKind(direct("lo", "http://127.0.0.1:3773/"))).toBe("loopback");
|
||||
expect(connectionRouteKind(direct("ts6", "http://[fd7a:115c:a1e0::1]:3773/"))).toBe("tailnet");
|
||||
expect(connectionRouteLabel(TAILNET)).toBe("Tailscale");
|
||||
expect(connectionRouteLabel(RELAY)).toBe("T3 Connect");
|
||||
});
|
||||
|
||||
it("places a new route after faster kinds and ahead of T3 Connect", () => {
|
||||
expect(insertRoute([RELAY], LAN)).toEqual([LAN, RELAY]);
|
||||
expect(insertRoute([LAN, RELAY], TAILNET)).toEqual([LAN, TAILNET, RELAY]);
|
||||
expect(insertRoute([TAILNET], LAN)).toEqual([LAN, TAILNET]);
|
||||
expect(insertRoute([LAN, TAILNET], RELAY)).toEqual([LAN, TAILNET, RELAY]);
|
||||
});
|
||||
|
||||
it("keeps a user's order when a saved route is replaced", () => {
|
||||
// The user preferred T3 Connect over the LAN; re-pairing the LAN keeps that.
|
||||
const repaired = direct("lan", "http://192.168.1.11:3773/");
|
||||
expect(upsertRoute([RELAY, LAN], repaired)).toEqual([RELAY, repaired]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import {
|
||||
isLocalLoopbackHost,
|
||||
isPrivateNetworkHost,
|
||||
isTailnetHost,
|
||||
} from "@t3tools/shared/hostClassification";
|
||||
import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
|
||||
import type { ConnectionTarget } from "./model.ts";
|
||||
|
||||
/**
|
||||
* A saved environment can hold several routes: T3 Connect, direct URLs (LAN,
|
||||
* tailnet, public), and SSH. The client connects over the first route in
|
||||
* preference order that answers as the expected environment, and moves back
|
||||
* to a better one when it becomes reachable again.
|
||||
*/
|
||||
|
||||
export type ConnectionRouteKind = "relay" | "loopback" | "lan" | "tailnet" | "public" | "ssh";
|
||||
|
||||
/** An environment has at most one T3 Connect route, so it needs no per-route id. */
|
||||
export const RELAY_ROUTE_ID = "relay";
|
||||
|
||||
export function connectionRouteId(target: ConnectionTarget): string {
|
||||
switch (target._tag) {
|
||||
case "PrimaryConnectionTarget":
|
||||
return "primary";
|
||||
case "RelayConnectionTarget":
|
||||
return RELAY_ROUTE_ID;
|
||||
case "BearerConnectionTarget":
|
||||
case "SshConnectionTarget":
|
||||
return target.connectionId;
|
||||
}
|
||||
}
|
||||
|
||||
/** Every route of an entry, preferred first. */
|
||||
export function connectionRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
|
||||
return [{ target: entry.target, profile: entry.profile }, ...(entry.alternateRoutes ?? [])];
|
||||
}
|
||||
|
||||
/** Builds an entry whose preferred route is the first of `routes`, which must not be empty. */
|
||||
export function entryWithRoutes(
|
||||
entry: ConnectionCatalogEntry,
|
||||
routes: ReadonlyArray<ConnectionRoute>,
|
||||
): ConnectionCatalogEntry {
|
||||
const [first, ...rest] = routes;
|
||||
if (first === undefined) {
|
||||
throw new Error("A saved environment needs at least one route.");
|
||||
}
|
||||
const { alternateRoutes: _previous, ...base } = entry;
|
||||
return {
|
||||
...base,
|
||||
target: first.target,
|
||||
profile: first.profile,
|
||||
...(rest.length === 0 ? {} : { alternateRoutes: rest }),
|
||||
};
|
||||
}
|
||||
|
||||
/** The entry a single route connects with. */
|
||||
export function routeEntry(
|
||||
entry: ConnectionCatalogEntry,
|
||||
route: ConnectionRoute,
|
||||
): ConnectionCatalogEntry {
|
||||
return entryWithRoutes(entry, [route]);
|
||||
}
|
||||
|
||||
/** The base URL of a direct route, or null for T3 Connect and SSH. */
|
||||
export function routeHttpBaseUrl(route: ConnectionRoute): string | null {
|
||||
if (route.target._tag === "PrimaryConnectionTarget") return route.target.httpBaseUrl;
|
||||
const profile = Option.getOrNull(route.profile);
|
||||
return profile?._tag === "BearerConnectionProfile" ? profile.httpBaseUrl : null;
|
||||
}
|
||||
|
||||
function routeHostname(route: ConnectionRoute): string | null {
|
||||
const httpBaseUrl = routeHttpBaseUrl(route);
|
||||
if (httpBaseUrl === null) return null;
|
||||
try {
|
||||
return new URL(httpBaseUrl).hostname;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function connectionRouteKind(route: ConnectionRoute): ConnectionRouteKind {
|
||||
switch (route.target._tag) {
|
||||
case "RelayConnectionTarget":
|
||||
return "relay";
|
||||
case "SshConnectionTarget":
|
||||
return "ssh";
|
||||
case "PrimaryConnectionTarget":
|
||||
case "BearerConnectionTarget": {
|
||||
const hostname = routeHostname(route);
|
||||
if (hostname === null) return "public";
|
||||
if (isLocalLoopbackHost(hostname)) return "loopback";
|
||||
if (isTailnetHost(hostname)) return "tailnet";
|
||||
return isPrivateNetworkHost(hostname) ? "lan" : "public";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ROUTE_KIND_RANK: Record<ConnectionRouteKind, number> = {
|
||||
loopback: 0,
|
||||
lan: 1,
|
||||
tailnet: 2,
|
||||
public: 3,
|
||||
ssh: 4,
|
||||
relay: 5,
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a newly added route goes: after every saved route of the same or a
|
||||
* faster kind, so LAN lands ahead of tailnet and both ahead of T3 Connect.
|
||||
* Users can reorder afterwards; this only picks a sensible starting point.
|
||||
*/
|
||||
export function insertRoute(
|
||||
routes: ReadonlyArray<ConnectionRoute>,
|
||||
route: ConnectionRoute,
|
||||
): ReadonlyArray<ConnectionRoute> {
|
||||
const rank = ROUTE_KIND_RANK[connectionRouteKind(route)];
|
||||
const index = routes.findIndex(
|
||||
(existing) => ROUTE_KIND_RANK[connectionRouteKind(existing)] > rank,
|
||||
);
|
||||
return index === -1
|
||||
? [...routes, route]
|
||||
: [...routes.slice(0, index), route, ...routes.slice(index)];
|
||||
}
|
||||
|
||||
/** Replaces the route with the same id in place, or inserts it by kind. */
|
||||
export function upsertRoute(
|
||||
routes: ReadonlyArray<ConnectionRoute>,
|
||||
route: ConnectionRoute,
|
||||
): ReadonlyArray<ConnectionRoute> {
|
||||
const id = connectionRouteId(route.target);
|
||||
return routes.some((existing) => connectionRouteId(existing.target) === id)
|
||||
? routes.map((existing) => (connectionRouteId(existing.target) === id ? route : existing))
|
||||
: insertRoute(routes, route);
|
||||
}
|
||||
|
||||
/**
|
||||
* A saved route that reaches the same address as `route`: the same bearer
|
||||
* URL, or the same SSH target (alias, host, user, and port, as desktop keys
|
||||
* its tunnels). Registering it again replaces that route, even when it was
|
||||
* saved under another id.
|
||||
*/
|
||||
export function findRouteToSameAddress(
|
||||
routes: ReadonlyArray<ConnectionRoute>,
|
||||
route: ConnectionRoute,
|
||||
): ConnectionRoute | undefined {
|
||||
const key = routeAddressKey(route);
|
||||
return key === null ? undefined : routes.find((existing) => routeAddressKey(existing) === key);
|
||||
}
|
||||
|
||||
function routeAddressKey(route: ConnectionRoute): string | null {
|
||||
const profile = Option.getOrNull(route.profile);
|
||||
switch (profile?._tag) {
|
||||
case "BearerConnectionProfile":
|
||||
return `bearer:${profile.httpBaseUrl.replace(/\/+$/, "")}`;
|
||||
case "SshConnectionProfile":
|
||||
return `ssh:${sshTargetKey(profile.target)}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Short user-facing route description: "LAN", "Tailscale", "T3 Connect", a URL, or an SSH host. */
|
||||
export function connectionRouteLabel(route: ConnectionRoute): string {
|
||||
switch (connectionRouteKind(route)) {
|
||||
case "relay":
|
||||
return "T3 Connect";
|
||||
case "loopback":
|
||||
return "This device";
|
||||
case "lan":
|
||||
return "LAN";
|
||||
case "tailnet":
|
||||
return "Tailscale";
|
||||
case "ssh": {
|
||||
const profile = Option.getOrNull(route.profile);
|
||||
return profile?._tag === "SshConnectionProfile"
|
||||
? `SSH ${profile.target.username ? `${profile.target.username}@` : ""}${profile.target.hostname}`
|
||||
: "SSH";
|
||||
}
|
||||
case "public":
|
||||
return routeHostname(route) ?? "Remote link";
|
||||
}
|
||||
}
|
||||
|
||||
/** The address shown under a route, or null for T3 Connect. */
|
||||
export function connectionRouteAddress(route: ConnectionRoute): string | null {
|
||||
if (route.target._tag === "SshConnectionTarget") {
|
||||
const profile = Option.getOrNull(route.profile);
|
||||
return profile?._tag === "SshConnectionProfile" ? profile.target.alias : null;
|
||||
}
|
||||
return routeHttpBaseUrl(route);
|
||||
}
|
||||
|
||||
/** Whether the environment can be reached through T3 Connect. */
|
||||
export function hasRelayRoute(
|
||||
entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">,
|
||||
): boolean {
|
||||
return [entry.target, ...(entry.alternateRoutes ?? []).map((route) => route.target)].some(
|
||||
(target) => target._tag === "RelayConnectionTarget",
|
||||
);
|
||||
}
|
||||
|
||||
/** One SSH target, as desktop keys its tunnels: alias, host, user, and port. */
|
||||
export function sshTargetKey(target: DesktopSshEnvironmentTarget): string {
|
||||
return JSON.stringify([target.alias, target.hostname, target.username, target.port]);
|
||||
}
|
||||
@@ -19,10 +19,12 @@ import * as ManagedRelay from "../relay/managedRelay.ts";
|
||||
import { remoteHttpClientLayer } from "../rpc/http.ts";
|
||||
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
|
||||
import { fetchEnvironmentSessionState } from "../state/session.ts";
|
||||
import type { ConnectionCatalogEntry } from "./catalog.ts";
|
||||
import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
|
||||
import * as Connectivity from "./connectivity.ts";
|
||||
import * as ConnectionDriver from "./driver.ts";
|
||||
import { BearerConnectionProfile } from "./catalog.ts";
|
||||
import {
|
||||
BearerConnectionTarget,
|
||||
ConnectionBlockedError,
|
||||
ConnectionTransientError,
|
||||
PrimaryConnectionTarget,
|
||||
@@ -73,6 +75,35 @@ const PREPARED_CONNECTION: PreparedConnection = {
|
||||
|
||||
const TEST_RPC_CLIENT = {} as WsRpcProtocolClient;
|
||||
|
||||
const LAN_TARGET = new BearerConnectionTarget({
|
||||
environmentId: TARGET.environmentId,
|
||||
label: TARGET.label,
|
||||
connectionId: "bearer:lan",
|
||||
});
|
||||
const LAN_ROUTE: ConnectionRoute = {
|
||||
target: LAN_TARGET,
|
||||
profile: Option.some(
|
||||
new BearerConnectionProfile({
|
||||
connectionId: LAN_TARGET.connectionId,
|
||||
environmentId: TARGET.environmentId,
|
||||
label: TARGET.label,
|
||||
httpBaseUrl: "http://192.168.1.10:3773/",
|
||||
wsBaseUrl: "ws://192.168.1.10:3773/",
|
||||
}),
|
||||
),
|
||||
};
|
||||
// LAN first, T3 Connect as the fallback.
|
||||
const LAN_THEN_RELAY_ENTRY: ConnectionCatalogEntry = {
|
||||
target: LAN_ROUTE.target,
|
||||
profile: LAN_ROUTE.profile,
|
||||
alternateRoutes: [{ target: RELAY_TARGET, profile: Option.none() }],
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
function preparedFor(target: ConnectionTarget): PreparedConnection {
|
||||
return { ...PREPARED_CONNECTION, target };
|
||||
}
|
||||
|
||||
function transient(message = "Connection failed.") {
|
||||
return new ConnectionTransientError({
|
||||
reason: "transport",
|
||||
@@ -125,6 +156,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
|
||||
) => Effect.Effect<PreparedConnection, ConnectionAttemptError>;
|
||||
readonly ready?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
|
||||
readonly probe?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
|
||||
readonly checkRoute?: (route: ConnectionRoute) => Effect.Effect<ConnectionDriver.RouteCheck>;
|
||||
}) {
|
||||
const networkStatus = yield* SubscriptionRef.make<NetworkStatus>(
|
||||
options?.networkStatus ?? "online",
|
||||
@@ -156,12 +188,13 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
|
||||
return PREPARED_CONNECTION;
|
||||
});
|
||||
|
||||
const connect = Effect.fn("TestConnectionDriver.connect")(function* (
|
||||
entry: ConnectionCatalogEntry,
|
||||
const checkRoute = (route: ConnectionRoute) =>
|
||||
options?.checkRoute?.(route) ?? Effect.succeed<ConnectionDriver.RouteCheck>("unchecked");
|
||||
|
||||
const connectRoute = Effect.fn("TestConnectionDriver.connectRoute")(function* (
|
||||
target: ConnectionTarget,
|
||||
reportProgress: (progress: ConnectionDriver.ConnectionDriverProgress) => Effect.Effect<void>,
|
||||
) {
|
||||
const target = entry.target;
|
||||
yield* reportProgress({ stage: "preparing" });
|
||||
const prepared = yield* prepare(target);
|
||||
yield* reportProgress({ stage: "opening", prepared });
|
||||
|
||||
@@ -186,6 +219,16 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
|
||||
return { prepared, session } satisfies ConnectionDriver.EnvironmentConnectionLease;
|
||||
});
|
||||
|
||||
const connect = Effect.fn("TestConnectionDriver.connect")(function* (
|
||||
entry: ConnectionCatalogEntry,
|
||||
reportProgress: (progress: ConnectionDriver.ConnectionDriverProgress) => Effect.Effect<void>,
|
||||
) {
|
||||
yield* reportProgress({ stage: "preparing" });
|
||||
return yield* ConnectionDriver.connectOverRoutes(entry, checkRoute, (route) =>
|
||||
connectRoute(route.target, reportProgress),
|
||||
);
|
||||
});
|
||||
|
||||
const dependencies = Layer.mergeAll(
|
||||
// Jitter at its maximum, so each retry waits exactly its ceiling: 2s, 4s, 8s...
|
||||
Layer.succeed(Random.Random, {
|
||||
@@ -204,7 +247,12 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
|
||||
),
|
||||
Layer.succeed(
|
||||
ConnectionDriver.ConnectionDriver,
|
||||
ConnectionDriver.ConnectionDriver.of({ connect }),
|
||||
ConnectionDriver.ConnectionDriver.of({
|
||||
connect,
|
||||
checkRoute: (_entry, route) => checkRoute(route),
|
||||
preflight: (_entry, route) =>
|
||||
checkRoute(route).pipe(Effect.map((check) => check === "answered")),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1336,7 +1384,9 @@ describe("EnvironmentSupervisor", () => {
|
||||
|
||||
it.effect("releases and reconnects a relay session when credentials change", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness();
|
||||
const harness = yield* makeHarness({
|
||||
prepare: () => Effect.succeed(preparedFor(RELAY_TARGET)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
@@ -1633,3 +1683,304 @@ describe("EnvironmentSupervisor", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("EnvironmentSupervisor routes", () => {
|
||||
it.effect("skips a silent LAN route and connects over T3 Connect", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: (route) =>
|
||||
Effect.succeed(route.target._tag === "BearerConnectionTarget" ? "silent" : "unchecked"),
|
||||
prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
const prepared = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared));
|
||||
expect(prepared.target._tag).toBe("RelayConnectionTarget");
|
||||
// The silent route never reached the resolver.
|
||||
expect(yield* Ref.get(harness.prepareCount)).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("moves to a blocked route's fallback instead of stopping", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: () => Effect.succeed("answered"),
|
||||
prepare: (_attempt, target) =>
|
||||
target._tag === "BearerConnectionTarget"
|
||||
? Effect.fail(blocked("The environment credential is invalid."))
|
||||
: Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
const prepared = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared));
|
||||
expect(prepared.target._tag).toBe("RelayConnectionTarget");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("tries every route when none answers the reachability check", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: () => Effect.succeed("silent"),
|
||||
prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
const prepared = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared));
|
||||
expect(prepared.target._tag).toBe("BearerConnectionTarget");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("still tries a silent LAN route after the T3 Connect route fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: (route) =>
|
||||
Effect.succeed(route.target._tag === "BearerConnectionTarget" ? "silent" : "unchecked"),
|
||||
// Signed out of T3 Connect; the LAN is up but its check timed out.
|
||||
prepare: (_attempt, target) =>
|
||||
target._tag === "RelayConnectionTarget"
|
||||
? Effect.fail(blocked("Sign in to T3 Connect."))
|
||||
: Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
|
||||
"BearerConnectionTarget",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps retrying when one route is blocked and another failed transiently", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: () => Effect.succeed("answered"),
|
||||
prepare: (_attempt, target) =>
|
||||
target._tag === "RelayConnectionTarget"
|
||||
? Effect.fail(blocked("Sign in to T3 Connect."))
|
||||
: Effect.fail(transient("LAN socket refused.")),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
// A blocked state would stop retrying; the LAN may come back.
|
||||
const state = yield* awaitState(supervisor.state, (value) => value.phase === "backoff");
|
||||
expect(state.lastFailure?._tag).toBe("ConnectionTransientError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("moves back to the LAN route when the network changes and it answers again", () =>
|
||||
Effect.gen(function* () {
|
||||
const lanReachable = yield* Ref.make(false);
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: (route) =>
|
||||
route.target._tag === "BearerConnectionTarget"
|
||||
? Ref.get(lanReachable).pipe(
|
||||
Effect.map((reachable) => (reachable ? "answered" : "silent")),
|
||||
)
|
||||
: Effect.succeed("unchecked"),
|
||||
prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 1,
|
||||
);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
|
||||
"RelayConnectionTarget",
|
||||
);
|
||||
|
||||
// Back home: the LAN answers, and a network change asks for a better route.
|
||||
yield* Ref.set(lanReachable, true);
|
||||
yield* harness.setNetworkStatus("unknown");
|
||||
yield* harness.setNetworkStatus("online");
|
||||
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 2,
|
||||
);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
|
||||
"BearerConnectionTarget",
|
||||
);
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("checks for a better route periodically while on a fallback", () =>
|
||||
Effect.gen(function* () {
|
||||
const lanReachable = yield* Ref.make(false);
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: (route) =>
|
||||
route.target._tag === "BearerConnectionTarget"
|
||||
? Ref.get(lanReachable).pipe(
|
||||
Effect.map((reachable) => (reachable ? "answered" : "silent")),
|
||||
)
|
||||
: Effect.succeed("unchecked"),
|
||||
prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 1,
|
||||
);
|
||||
yield* Ref.set(lanReachable, true);
|
||||
yield* TestClock.adjust("60 seconds");
|
||||
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 2,
|
||||
);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
|
||||
"BearerConnectionTarget",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not retry a better route that answered but failed to connect", () =>
|
||||
Effect.gen(function* () {
|
||||
const lanAnswers = yield* Ref.make(false);
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: (route) =>
|
||||
route.target._tag === "BearerConnectionTarget"
|
||||
? Ref.get(lanAnswers).pipe(Effect.map((answers) => (answers ? "answered" : "silent")))
|
||||
: Effect.succeed("unchecked"),
|
||||
// The LAN answers its check but the socket never opens.
|
||||
prepare: (_attempt, target) =>
|
||||
target._tag === "BearerConnectionTarget"
|
||||
? Effect.fail(transient("Socket refused."))
|
||||
: Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 1,
|
||||
);
|
||||
yield* Ref.set(lanAnswers, true);
|
||||
yield* TestClock.adjust("60 seconds");
|
||||
// The switch lands back on T3 Connect.
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 2,
|
||||
);
|
||||
const preparesAfterSwitch = yield* Ref.get(harness.prepareCount);
|
||||
|
||||
// The failed LAN is cooling down, so the next periodic check leaves the
|
||||
// session alone.
|
||||
yield* TestClock.adjust("60 seconds");
|
||||
yield* Effect.yieldNow;
|
||||
expect(yield* Ref.get(harness.prepareCount)).toBe(preparesAfterSwitch);
|
||||
expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
|
||||
phase: "connected",
|
||||
generation: 2,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stays on the preferred route without checking other routes", () =>
|
||||
Effect.gen(function* () {
|
||||
const checks = yield* Ref.make(0);
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: () => Ref.update(checks, (count) => count + 1).pipe(Effect.as("answered")),
|
||||
prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
const checksAtConnect = yield* Ref.get(checks);
|
||||
yield* harness.setNetworkStatus("unknown");
|
||||
yield* harness.setNetworkStatus("online");
|
||||
yield* TestClock.adjust("5 minutes");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* Ref.get(checks)).toBe(checksAtConnect);
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("moves off a dead LAN socket when the phone switches to cellular", () =>
|
||||
Effect.gen(function* () {
|
||||
const lanReachable = yield* Ref.make(true);
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: (route) =>
|
||||
route.target._tag === "BearerConnectionTarget"
|
||||
? Ref.get(lanReachable).pipe(
|
||||
Effect.map((reachable) => (reachable ? "answered" : "silent")),
|
||||
)
|
||||
: Effect.succeed("unchecked"),
|
||||
prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
|
||||
// The LAN socket never answers once the phone has left the network.
|
||||
probe: () =>
|
||||
Ref.get(lanReachable).pipe(
|
||||
Effect.flatMap((reachable) => (reachable ? Effect.void : Effect.never)),
|
||||
),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 1,
|
||||
);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
|
||||
"BearerConnectionTarget",
|
||||
);
|
||||
|
||||
yield* Ref.set(lanReachable, false);
|
||||
yield* harness.wake("network-changed");
|
||||
yield* TestClock.adjust("3 seconds");
|
||||
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 2,
|
||||
);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
|
||||
"RelayConnectionTarget",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a LAN session when the T3 Connect account changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
checkRoute: () => Effect.succeed("answered"),
|
||||
prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
yield* harness.wake("credentials-changed");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
|
||||
expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
|
||||
phase: "connected",
|
||||
generation: 1,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -15,7 +15,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
|
||||
import type { ConnectionCatalogEntry } from "./catalog.ts";
|
||||
import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
|
||||
import * as Connectivity from "./connectivity.ts";
|
||||
import * as ConnectionDriver from "./driver.ts";
|
||||
import {
|
||||
@@ -30,15 +30,23 @@ import * as RpcSession from "../rpc/session.ts";
|
||||
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
|
||||
import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
|
||||
import * as ConnectionWakeups from "./wakeups.ts";
|
||||
import { connectionRouteId, connectionRoutes, entryWithRoutes } from "./routes.ts";
|
||||
|
||||
const RETRY_BASE_DELAY_MS = 1_000;
|
||||
const RETRY_MAX_DELAY_MS = 300_000;
|
||||
const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds";
|
||||
const establishmentTimeout = Duration.fromInputUnsafe(CONNECTION_ESTABLISHMENT_TIMEOUT);
|
||||
const CONNECTION_PROBE_TIMEOUT = "15 seconds";
|
||||
// Mobile resumes, explicit retries, and offline events want a fast answer:
|
||||
// the user is waiting, or the network may be gone.
|
||||
const QUICK_CONNECTION_PROBE_TIMEOUT = "3 seconds";
|
||||
const BACKOFF_RESET_AFTER_MS = 30_000;
|
||||
// While connected over a fallback route, how often to look for a better one.
|
||||
// Network changes and returning to the app also trigger a check.
|
||||
const BETTER_ROUTE_CHECK_INTERVAL = "60 seconds";
|
||||
// A better route that answered the check but then failed to connect is not
|
||||
// tried again for this long, so a flaky LAN cannot bounce the connection.
|
||||
const BETTER_ROUTE_COOLDOWN_MS = 300_000;
|
||||
|
||||
interface SupervisorIntent {
|
||||
readonly desired: boolean;
|
||||
@@ -50,7 +58,8 @@ type SupervisorSignal =
|
||||
| { readonly _tag: "DisconnectRequested" }
|
||||
| { readonly _tag: "RetryRequested" }
|
||||
| { readonly _tag: "NetworkChanged"; readonly network: NetworkStatus }
|
||||
| { readonly _tag: "Wakeup"; readonly reason: ConnectionWakeups.ConnectionWakeup };
|
||||
| { readonly _tag: "Wakeup"; readonly reason: ConnectionWakeups.ConnectionWakeup }
|
||||
| { readonly _tag: "BetterRouteAvailable"; readonly routeId: string };
|
||||
|
||||
interface PendingRetryTrace {
|
||||
readonly previousAttempt: Tracer.Span;
|
||||
@@ -236,8 +245,13 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
| ConnectionWakeups.ConnectionWakeups
|
||||
> {
|
||||
const target = entry.target;
|
||||
// Relay-specific handling applies when any route is T3 Connect, since the
|
||||
// attempt or the live session may be using it.
|
||||
const usesRelay = connectionRoutes(entry).some(
|
||||
(route) => route.target._tag === "RelayConnectionTarget",
|
||||
);
|
||||
const setupTimeoutDetail = `${target.label} did not respond during connection setup.${
|
||||
target._tag === "RelayConnectionTarget" ? ` ${NETWORK_BLOCKING_HINT}` : ""
|
||||
usesRelay ? ` ${NETWORK_BLOCKING_HINT}` : ""
|
||||
}`;
|
||||
yield* annotateTarget(target);
|
||||
|
||||
@@ -265,6 +279,64 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
);
|
||||
const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
|
||||
const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
|
||||
const routes = connectionRoutes(entry);
|
||||
// Set when a better route answered while connected over a worse one; the
|
||||
// replacement attempt tries it first. Cleared once an attempt starts.
|
||||
const preferredRouteId = yield* Ref.make(Option.none<string>());
|
||||
// Monotonic deadline per route that answered a check but failed to connect.
|
||||
const routeCooldowns = yield* Ref.make<ReadonlyMap<string, bigint>>(new Map());
|
||||
|
||||
const attemptEntry = Effect.gen(function* () {
|
||||
const preferred = yield* Ref.getAndSet(preferredRouteId, Option.none());
|
||||
if (Option.isNone(preferred)) return entry;
|
||||
const route = routes.find(
|
||||
(candidate) => connectionRouteId(candidate.target) === preferred.value,
|
||||
);
|
||||
return route === undefined
|
||||
? entry
|
||||
: entryWithRoutes(entry, [route, ...routes.filter((candidate) => candidate !== route)]);
|
||||
});
|
||||
|
||||
const routeIndex = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
|
||||
routes.findIndex(
|
||||
(route) => connectionRouteId(route.target) === connectionRouteId(lease.prepared.target),
|
||||
);
|
||||
|
||||
/**
|
||||
* Preflights the routes ranked above the one in use and signals the best
|
||||
* that would connect. Routes without a cheap check (T3 Connect, SSH) never
|
||||
* pass, so they are fallbacks, not destinations.
|
||||
*/
|
||||
const checkBetterRoutes = Effect.fnUntraced(function* (
|
||||
lease: ConnectionDriver.EnvironmentConnectionLease,
|
||||
) {
|
||||
const current = routeIndex(lease);
|
||||
if (current <= 0) return;
|
||||
const now = yield* Clock.monotonicTimeNanos;
|
||||
const cooldowns = yield* Ref.get(routeCooldowns);
|
||||
const better = routes
|
||||
.slice(0, current)
|
||||
.filter((route) => (cooldowns.get(connectionRouteId(route.target)) ?? 0n) <= now);
|
||||
const passed = yield* Effect.forEach(
|
||||
better,
|
||||
(route: ConnectionRoute) => driver.preflight(entry, route),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const index = passed.indexOf(true);
|
||||
if (index === -1) return;
|
||||
// The check may outlive the session it was asked about.
|
||||
const live = yield* SubscriptionRef.get(session);
|
||||
if (Option.isNone(live) || live.value !== lease.session) return;
|
||||
yield* signal({
|
||||
_tag: "BetterRouteAvailable",
|
||||
routeId: connectionRouteId(better[index]!.target),
|
||||
});
|
||||
});
|
||||
|
||||
// One check at a time; a trigger during a check is dropped, not queued.
|
||||
const betterRouteChecks = yield* Queue.dropping<ConnectionDriver.EnvironmentConnectionLease>(1);
|
||||
const requestBetterRouteCheck = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
|
||||
routeIndex(lease) > 0 ? Queue.offer(betterRouteChecks, lease).pipe(Effect.asVoid) : Effect.void;
|
||||
|
||||
const clearLease = Effect.all(
|
||||
[SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
|
||||
@@ -309,7 +381,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
generation: number,
|
||||
lastFailure: ConnectionAttemptError | null,
|
||||
) {
|
||||
return yield* driver.connect(entry, (progress) =>
|
||||
return yield* driver.connect(yield* attemptEntry, (progress) =>
|
||||
reportProgress(attempt, generation, lastFailure, progress),
|
||||
);
|
||||
});
|
||||
@@ -362,7 +434,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
lastFailure: ConnectionAttemptError | null,
|
||||
pendingRetry: Option.Option<PendingRetryTrace>,
|
||||
) {
|
||||
if (target._tag === "RelayConnectionTarget") {
|
||||
if (usesRelay) {
|
||||
return yield* traceRelayEstablishment(
|
||||
establishConnection(attempt, generation, lastFailure),
|
||||
attempt,
|
||||
@@ -395,12 +467,13 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
}
|
||||
break;
|
||||
case "ConnectRequested":
|
||||
case "BetterRouteAvailable":
|
||||
break;
|
||||
case "Wakeup":
|
||||
if (next.reason === "application-active-reconnect") {
|
||||
return true;
|
||||
}
|
||||
if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
|
||||
if (next.reason === "credentials-changed" && usesRelay) {
|
||||
yield* logManagedRelayAccountChange;
|
||||
return false;
|
||||
}
|
||||
@@ -411,10 +484,22 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
|
||||
// Signals that end a connected lease whatever its health: "reset" ends it
|
||||
// and restarts the retry ladder, "end" ends it, undefined keeps it.
|
||||
const connectedLeaseEnd = Effect.fnUntraced(function* (next: SupervisorSignal) {
|
||||
const isRelayLease = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
|
||||
lease.prepared.target._tag === "RelayConnectionTarget";
|
||||
|
||||
const connectedLeaseEnd = Effect.fnUntraced(function* (
|
||||
next: SupervisorSignal,
|
||||
lease: ConnectionDriver.EnvironmentConnectionLease,
|
||||
) {
|
||||
if (next._tag === "DisconnectRequested") {
|
||||
return "end" as const;
|
||||
}
|
||||
if (next._tag === "BetterRouteAvailable") {
|
||||
// Replaced like a long resume: the new attempt prefers the better route
|
||||
// and its session takes over the durable subscriptions.
|
||||
yield* Ref.set(preferredRouteId, Option.some(next.routeId));
|
||||
return "reset" as const;
|
||||
}
|
||||
if (next._tag !== "Wakeup") {
|
||||
return undefined;
|
||||
}
|
||||
@@ -424,7 +509,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
// out, so a long background resume replaces the session at once.
|
||||
return "reset" as const;
|
||||
}
|
||||
if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
|
||||
// Only a session over T3 Connect holds the old account's credential.
|
||||
if (next.reason === "credentials-changed" && isRelayLease(lease)) {
|
||||
yield* logManagedRelayAccountChange;
|
||||
return "end" as const;
|
||||
}
|
||||
@@ -443,11 +529,13 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
if (next.reason === "application-active") {
|
||||
return CONNECTION_PROBE_TIMEOUT;
|
||||
}
|
||||
return next.reason === "application-active-probe"
|
||||
// A socket opened on the previous network may now be unroutable.
|
||||
return next.reason === "application-active-probe" || next.reason === "network-changed"
|
||||
? QUICK_CONNECTION_PROBE_TIMEOUT
|
||||
: undefined;
|
||||
case "ConnectRequested":
|
||||
case "DisconnectRequested":
|
||||
case "BetterRouteAvailable":
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
@@ -469,12 +557,26 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
next._tag === "RetryRequested" ? Ref.set(resetRetryState, false) : Effect.void,
|
||||
),
|
||||
);
|
||||
if (routes.length > 1 && routeIndex(lease) > 0) {
|
||||
yield* Stream.tick(BETTER_ROUTE_CHECK_INTERVAL).pipe(
|
||||
Stream.drop(1),
|
||||
Stream.runForEach(() => requestBetterRouteCheck(lease)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
for (;;) {
|
||||
const next = yield* takeSignal;
|
||||
const end = yield* connectedLeaseEnd(next);
|
||||
const end = yield* connectedLeaseEnd(next, lease);
|
||||
if (end !== undefined) {
|
||||
return end === "reset";
|
||||
}
|
||||
// A new network or a return to the app may have brought a better route back.
|
||||
if (
|
||||
(next._tag === "NetworkChanged" && next.network !== "offline") ||
|
||||
(next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason))
|
||||
) {
|
||||
yield* requestBetterRouteCheck(lease);
|
||||
}
|
||||
const probeTimeout = probeTimeoutFor(next);
|
||||
if (probeTimeout === undefined) {
|
||||
continue;
|
||||
@@ -508,7 +610,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
yield* probeEvent.exit;
|
||||
break;
|
||||
}
|
||||
const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal);
|
||||
const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal, lease);
|
||||
if (endDuringProbe !== undefined) {
|
||||
yield* Fiber.interrupt(probe);
|
||||
return endDuringProbe === "reset";
|
||||
@@ -532,6 +634,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
pendingRetry: Option.Option<PendingRetryTrace>,
|
||||
ignoreOffline: boolean,
|
||||
) {
|
||||
const switchingTo = yield* Ref.get(preferredRouteId);
|
||||
yield* SubscriptionRef.set(prepared, Option.none());
|
||||
const establishment = yield* Effect.raceAllFirst([
|
||||
exitUnlessInterrupted(
|
||||
@@ -548,7 +651,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
resetRetry,
|
||||
})),
|
||||
),
|
||||
Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
|
||||
// Each route may use the full setup time before the next is tried.
|
||||
Effect.sleep(Duration.times(establishmentTimeout, routes.length)).pipe(
|
||||
Effect.as<EstablishmentEvent>({ _tag: "TimedOut" }),
|
||||
),
|
||||
]);
|
||||
@@ -595,6 +699,16 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
}
|
||||
|
||||
const active = establishment.exit.value;
|
||||
if (Option.isSome(switchingTo)) {
|
||||
const landed = connectionRouteId(active.lease.prepared.target);
|
||||
if (landed !== switchingTo.value) {
|
||||
const until =
|
||||
(yield* Clock.monotonicTimeNanos) + BigInt(BETTER_ROUTE_COOLDOWN_MS) * 1_000_000n;
|
||||
yield* Ref.update(routeCooldowns, (current) =>
|
||||
new Map(current).set(switchingTo.value, until),
|
||||
);
|
||||
}
|
||||
}
|
||||
const currentIntent = yield* Ref.get(intent);
|
||||
if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
|
||||
return {
|
||||
@@ -654,21 +768,25 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
const next = yield* Queue.take(signals);
|
||||
switch (next._tag) {
|
||||
case "Wakeup":
|
||||
return ConnectionWakeups.isApplicationActiveWakeup(next.reason);
|
||||
return ConnectionWakeups.resetsRetryBackoff(next.reason);
|
||||
case "ConnectRequested":
|
||||
case "DisconnectRequested":
|
||||
case "RetryRequested":
|
||||
case "NetworkChanged":
|
||||
return false;
|
||||
case "BetterRouteAvailable":
|
||||
break;
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// A better route only matters to a live session, so idle states ignore it.
|
||||
const waitForSignal = Queue.take(signals).pipe(
|
||||
Effect.repeat({ while: (next) => next._tag === "BetterRouteAvailable" }),
|
||||
Effect.map(
|
||||
(next) => next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason),
|
||||
(next) => next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -810,6 +928,11 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Queue.take(betterRouteChecks).pipe(
|
||||
Effect.flatMap(checkBetterRoutes),
|
||||
Effect.forever,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* run().pipe(Effect.forkScoped);
|
||||
|
||||
const connect = Ref.update(intent, (current) => ({
|
||||
|
||||
@@ -6,9 +6,12 @@ export type ConnectionWakeup =
|
||||
| "application-active"
|
||||
| "application-active-probe"
|
||||
| "application-active-reconnect"
|
||||
| "credentials-changed";
|
||||
| "credentials-changed"
|
||||
// The device moved to a different network (another Wi-Fi, Wi-Fi to
|
||||
// cellular) while staying online. Saved routes may have changed reach.
|
||||
| "network-changed";
|
||||
|
||||
export function isApplicationActiveWakeup(reason: ConnectionWakeup): boolean {
|
||||
function isApplicationActiveWakeup(reason: ConnectionWakeup): boolean {
|
||||
return (
|
||||
reason === "application-active" ||
|
||||
reason === "application-active-probe" ||
|
||||
@@ -16,6 +19,11 @@ export function isApplicationActiveWakeup(reason: ConnectionWakeup): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** Conditions changed enough that a pending retry should run now, from the first rung. */
|
||||
export function resetsRetryBackoff(reason: ConnectionWakeup): boolean {
|
||||
return isApplicationActiveWakeup(reason) || reason === "network-changed";
|
||||
}
|
||||
|
||||
// A long resume replaces the session, and the new session subscribes on its own.
|
||||
export function shouldResubscribeAfterWakeup(reason: ConnectionWakeup): boolean {
|
||||
return reason === "application-active" || reason === "application-active-probe";
|
||||
|
||||
@@ -59,8 +59,14 @@ export class PrimaryEnvironmentAuth extends Context.Service<
|
||||
export class SshEnvironmentGateway extends Context.Service<
|
||||
SshEnvironmentGateway,
|
||||
{
|
||||
/**
|
||||
* Starts or reuses the remote server and pairs with it. With
|
||||
* `expectedEnvironmentId`, a server that is a different machine fails
|
||||
* before its one-time pairing credential is spent.
|
||||
*/
|
||||
readonly provision: (
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
expectedEnvironmentId?: EnvironmentId,
|
||||
) => Effect.Effect<ProvisionedSshEnvironment, ConnectionAttemptError>;
|
||||
readonly prepare: (input: {
|
||||
readonly connectionId: string;
|
||||
|
||||
@@ -12,7 +12,7 @@ import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { ConnectionRegistration } from "../connection/catalog.ts";
|
||||
import type { ConnectionTarget } from "../connection/model.ts";
|
||||
import type { ConnectionTarget, PersistedConnectionTarget } from "../connection/model.ts";
|
||||
|
||||
export class ConnectionPersistenceError extends Schema.TaggedError<ConnectionPersistenceError>()(
|
||||
"ConnectionPersistenceError",
|
||||
@@ -21,6 +21,7 @@ export class ConnectionPersistenceError extends Schema.TaggedError<ConnectionPer
|
||||
"list-targets",
|
||||
"list-disabled-targets",
|
||||
"register-connection",
|
||||
"set-connection-routes",
|
||||
"remove-connection",
|
||||
"set-connection-enabled",
|
||||
"load-shell",
|
||||
@@ -52,10 +53,23 @@ export class ConnectionTargetStore extends Context.Service<
|
||||
export class ConnectionRegistrationStore extends Context.Service<
|
||||
ConnectionRegistrationStore,
|
||||
{
|
||||
/**
|
||||
* Saves one route's records and sets the environment's full route list,
|
||||
* preferred first. Records of routes missing from `routes` are dropped.
|
||||
*/
|
||||
readonly register: (
|
||||
registration: ConnectionRegistration,
|
||||
routes: ReadonlyArray<PersistedConnectionTarget>,
|
||||
) => Effect.Effect<void, ConnectionPersistenceError>;
|
||||
/** Reorders or drops routes without adding one. `routes` must not be empty. */
|
||||
readonly setRoutes: (
|
||||
environmentId: EnvironmentId,
|
||||
routes: ReadonlyArray<PersistedConnectionTarget>,
|
||||
) => Effect.Effect<void, ConnectionPersistenceError>;
|
||||
/** Forgets the environment and every route it had. */
|
||||
readonly remove: (
|
||||
environmentId: EnvironmentId,
|
||||
) => Effect.Effect<void, ConnectionPersistenceError>;
|
||||
readonly remove: (target: ConnectionTarget) => Effect.Effect<void, ConnectionPersistenceError>;
|
||||
readonly setEnabled: (
|
||||
environmentId: EnvironmentId,
|
||||
enabled: boolean,
|
||||
|
||||
@@ -27,6 +27,8 @@ import {
|
||||
import {
|
||||
ConnectionCatalogDocument,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
catalogRoutes,
|
||||
setRoutesInCatalog,
|
||||
putRemoteDpopTokenInCatalog,
|
||||
registerConnectionInCatalog,
|
||||
removeConnectionFromCatalog,
|
||||
@@ -123,7 +125,7 @@ describe("ConnectionCatalogDocument", () => {
|
||||
expect(yield* afterRemoval.get(entry)).toBe("off");
|
||||
|
||||
yield* permissions.set(entry, "read");
|
||||
document = removeConnectionFromCatalog(document, BEARER_TARGET);
|
||||
document = removeConnectionFromCatalog(document, ENVIRONMENT_ID);
|
||||
const afterCatalogRemoval = yield* makeGitHubRoutingPermissions(storage);
|
||||
expect(yield* afterCatalogRemoval.get(entry)).toBe("off");
|
||||
}),
|
||||
@@ -273,7 +275,7 @@ describe("ConnectionCatalogDocument", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(removeConnectionFromCatalog(registered, BEARER_TARGET)).toEqual(
|
||||
expect(removeConnectionFromCatalog(registered, ENVIRONMENT_ID)).toEqual(
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
);
|
||||
});
|
||||
@@ -295,7 +297,7 @@ describe("ConnectionCatalogDocument", () => {
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
new RelayConnectionRegistration({ target: RELAY_TARGET }),
|
||||
);
|
||||
const removed = removeConnectionFromCatalog(registered, RELAY_TARGET);
|
||||
const removed = removeConnectionFromCatalog(registered, ENVIRONMENT_ID);
|
||||
|
||||
expect(putRemoteDpopTokenInCatalog(removed, REMOTE_TOKEN)).toEqual(
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
@@ -309,7 +311,7 @@ describe("ConnectionCatalogDocument", () => {
|
||||
);
|
||||
const refreshed = putRemoteDpopTokenInCatalog(registered, REMOTE_TOKEN);
|
||||
|
||||
expect(removeConnectionFromCatalog(refreshed, RELAY_TARGET)).toEqual(
|
||||
expect(removeConnectionFromCatalog(refreshed, ENVIRONMENT_ID)).toEqual(
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
);
|
||||
});
|
||||
@@ -382,7 +384,9 @@ describe("ConnectionCatalogDocument", () => {
|
||||
}),
|
||||
).disabledEnvironmentIds,
|
||||
).toEqual([ENVIRONMENT_ID]);
|
||||
expect(removeConnectionFromCatalog(disabled, BEARER_TARGET).disabledEnvironmentIds).toEqual([]);
|
||||
expect(removeConnectionFromCatalog(disabled, ENVIRONMENT_ID).disabledEnvironmentIds).toEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
it("persists the normalized SSH profile beside its target", () => {
|
||||
@@ -411,4 +415,48 @@ describe("ConnectionCatalogDocument", () => {
|
||||
expect(document.profiles).toEqual([profile]);
|
||||
expect(document.credentials).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps every route of an environment and drops only a removed route's records", () => {
|
||||
const withBearer = registerConnectionInCatalog(
|
||||
{ ...EMPTY_CONNECTION_CATALOG_DOCUMENT, remoteDpopTokens: [REMOTE_TOKEN] },
|
||||
new BearerConnectionRegistration({
|
||||
target: BEARER_TARGET,
|
||||
profile: BEARER_PROFILE,
|
||||
credential: BEARER_CREDENTIAL,
|
||||
}),
|
||||
);
|
||||
const withRelay = registerConnectionInCatalog(
|
||||
withBearer,
|
||||
new RelayConnectionRegistration({ target: RELAY_TARGET }),
|
||||
[BEARER_TARGET, RELAY_TARGET],
|
||||
);
|
||||
expect(catalogRoutes(withRelay, ENVIRONMENT_ID)).toEqual([BEARER_TARGET, RELAY_TARGET]);
|
||||
expect(withRelay.credentials).toHaveLength(1);
|
||||
|
||||
// Dropping the bearer route forgets its credential; T3 Connect keeps its token.
|
||||
const relayOnly = setRoutesInCatalog(withRelay, ENVIRONMENT_ID, [RELAY_TARGET]);
|
||||
expect(relayOnly.targets).toEqual([RELAY_TARGET]);
|
||||
expect(relayOnly.profiles).toEqual([]);
|
||||
expect(relayOnly.credentials).toEqual([]);
|
||||
expect(relayOnly.remoteDpopTokens).toEqual([REMOTE_TOKEN]);
|
||||
|
||||
// Dropping T3 Connect forgets its token; the bearer route keeps its records.
|
||||
const bearerOnly = setRoutesInCatalog(withRelay, ENVIRONMENT_ID, [BEARER_TARGET]);
|
||||
expect(bearerOnly.credentials).toHaveLength(1);
|
||||
expect(bearerOnly.remoteDpopTokens).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps an environment's position in the catalog when its routes change", () => {
|
||||
const other = new RelayConnectionTarget({
|
||||
environmentId: EnvironmentId.make("environment-2"),
|
||||
label: "Other",
|
||||
});
|
||||
const document = {
|
||||
...EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
targets: [RELAY_TARGET, other],
|
||||
};
|
||||
expect(
|
||||
setRoutesInCatalog(document, ENVIRONMENT_ID, [BEARER_TARGET, RELAY_TARGET]).targets,
|
||||
).toEqual([BEARER_TARGET, RELAY_TARGET, other]);
|
||||
});
|
||||
});
|
||||
@@ -70,58 +70,77 @@ function connectionIdOf(target: ConnectionTarget): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
function removeConnectionMetadata(
|
||||
function routeKey(target: ConnectionTarget): string {
|
||||
return connectionIdOf(target) ?? target._tag;
|
||||
}
|
||||
|
||||
function removeRouteMetadata(
|
||||
document: ConnectionCatalogDocument,
|
||||
target: ConnectionTarget,
|
||||
removeRemoteToken: boolean,
|
||||
removed: ReadonlyArray<ConnectionTarget>,
|
||||
): ConnectionCatalogDocument {
|
||||
const connectionId = connectionIdOf(target);
|
||||
const connectionIds = new Set(removed.flatMap((target) => connectionIdOf(target) ?? []));
|
||||
const relayRemoved = removed.some((target) => target._tag === "RelayConnectionTarget");
|
||||
const environmentIds = new Set(removed.map((target) => target.environmentId));
|
||||
return {
|
||||
...document,
|
||||
targets: removeCatalogValue(
|
||||
document.targets,
|
||||
(value) => value.environmentId,
|
||||
target.environmentId,
|
||||
),
|
||||
profiles:
|
||||
connectionId === null
|
||||
? document.profiles
|
||||
: removeCatalogValue(document.profiles, (value) => value.connectionId, connectionId),
|
||||
credentials:
|
||||
connectionId === null
|
||||
? document.credentials
|
||||
: removeCatalogValue(document.credentials, (value) => value.connectionId, connectionId),
|
||||
remoteDpopTokens: removeRemoteToken
|
||||
? removeCatalogValue(
|
||||
document.remoteDpopTokens,
|
||||
(value) => value.environmentId,
|
||||
target.environmentId,
|
||||
)
|
||||
profiles: document.profiles.filter((value) => !connectionIds.has(value.connectionId)),
|
||||
credentials: document.credentials.filter((value) => !connectionIds.has(value.connectionId)),
|
||||
// The DPoP token belongs to the T3 Connect route.
|
||||
remoteDpopTokens: relayRemoved
|
||||
? document.remoteDpopTokens.filter((value) => !environmentIds.has(value.environmentId))
|
||||
: document.remoteDpopTokens,
|
||||
// Re-registration passes `removeRemoteToken: false` and must keep the
|
||||
// switched-off flag; only a real removal clears it.
|
||||
disabledEnvironmentIds: removeRemoteToken
|
||||
? removeCatalogValue(document.disabledEnvironmentIds, (value) => value, target.environmentId)
|
||||
: document.disabledEnvironmentIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An environment's saved routes in preference order. Targets of one
|
||||
* environment keep their relative order in `targets`, so a document written
|
||||
* before routes existed is one environment with one route.
|
||||
*/
|
||||
export function catalogRoutes(
|
||||
document: ConnectionCatalogDocument,
|
||||
environmentId: EnvironmentId,
|
||||
): ReadonlyArray<PersistedConnectionTarget> {
|
||||
return document.targets.filter((target) => target.environmentId === environmentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces an environment's routes with `routes`, preferred first. Records
|
||||
* owned by a dropped route go with it; the environment keeps its position in
|
||||
* the catalog. An empty list leaves the environment's other records in place;
|
||||
* use `removeConnectionFromCatalog` to forget the environment.
|
||||
*/
|
||||
export function setRoutesInCatalog(
|
||||
document: ConnectionCatalogDocument,
|
||||
environmentId: EnvironmentId,
|
||||
routes: ReadonlyArray<PersistedConnectionTarget>,
|
||||
): ConnectionCatalogDocument {
|
||||
const kept = new Set(routes.map(routeKey));
|
||||
const dropped = catalogRoutes(document, environmentId).filter(
|
||||
(target) => !kept.has(routeKey(target)),
|
||||
);
|
||||
const firstIndex = document.targets.findIndex((target) => target.environmentId === environmentId);
|
||||
const others = document.targets.filter((target) => target.environmentId !== environmentId);
|
||||
const insertAt =
|
||||
firstIndex === -1
|
||||
? others.length
|
||||
: document.targets.slice(0, firstIndex).filter((t) => t.environmentId !== environmentId)
|
||||
.length;
|
||||
return {
|
||||
...removeRouteMetadata(document, dropped),
|
||||
targets: [...others.slice(0, insertAt), ...routes, ...others.slice(insertAt)],
|
||||
};
|
||||
}
|
||||
|
||||
/** Saves one route of an environment, keeping its other routes. */
|
||||
export function registerConnectionInCatalog(
|
||||
document: ConnectionCatalogDocument,
|
||||
registration: ConnectionRegistration,
|
||||
routes: ReadonlyArray<PersistedConnectionTarget> = [registration.target],
|
||||
): ConnectionCatalogDocument {
|
||||
const target = registration.target;
|
||||
const previous = document.targets.find(
|
||||
(candidate) => candidate.environmentId === target.environmentId,
|
||||
);
|
||||
const cleaned =
|
||||
previous === undefined ? document : removeConnectionMetadata(document, previous, false);
|
||||
// Re-registering (for example editing a label or URL) keeps the disabled
|
||||
// flag; only `setConnectionEnabledInCatalog` or removal changes it.
|
||||
const next: ConnectionCatalogDocument = {
|
||||
...cleaned,
|
||||
targets: replaceCatalogValue(cleaned.targets, (value) => value.environmentId, target),
|
||||
};
|
||||
const next = setRoutesInCatalog(document, registration.target.environmentId, routes);
|
||||
|
||||
switch (registration._tag) {
|
||||
case "RelayConnectionRegistration":
|
||||
@@ -151,19 +170,32 @@ export function registerConnectionInCatalog(
|
||||
}
|
||||
}
|
||||
|
||||
/** Forgets an environment and every route it had. */
|
||||
export function removeConnectionFromCatalog(
|
||||
document: ConnectionCatalogDocument,
|
||||
target: ConnectionTarget,
|
||||
environmentId: EnvironmentId,
|
||||
): ConnectionCatalogDocument {
|
||||
const next = removeConnectionMetadata(document, target, true);
|
||||
return document.githubRoutingPermissions === undefined
|
||||
? next
|
||||
: {
|
||||
...next,
|
||||
githubRoutingPermissions: document.githubRoutingPermissions.filter(
|
||||
(permission) => permission.environmentId !== target.environmentId,
|
||||
),
|
||||
};
|
||||
const next = setRoutesInCatalog(document, environmentId, []);
|
||||
return {
|
||||
...next,
|
||||
remoteDpopTokens: removeCatalogValue(
|
||||
next.remoteDpopTokens,
|
||||
(value) => value.environmentId,
|
||||
environmentId,
|
||||
),
|
||||
disabledEnvironmentIds: removeCatalogValue(
|
||||
next.disabledEnvironmentIds,
|
||||
(value) => value,
|
||||
environmentId,
|
||||
),
|
||||
...(next.githubRoutingPermissions === undefined
|
||||
? {}
|
||||
: {
|
||||
githubRoutingPermissions: next.githubRoutingPermissions.filter(
|
||||
(permission) => permission.environmentId !== environmentId,
|
||||
),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Flips the disabled flag for a saved environment; unknown ids are ignored. */
|
||||
|
||||
@@ -161,6 +161,27 @@ export function createEnvironmentCatalogAtoms<R, E>(
|
||||
Effect.flatMap((registry) => registry.setEnabled(input.environmentId, input.enabled)),
|
||||
),
|
||||
});
|
||||
const removeRoute = createRuntimeCommand(runtime, {
|
||||
label: "environment-catalog:remove-route",
|
||||
scheduler: commandScheduler,
|
||||
concurrency: serial,
|
||||
execute: (input: { readonly environmentId: EnvironmentIdType; readonly routeId: string }) =>
|
||||
EnvironmentRegistry.EnvironmentRegistry.pipe(
|
||||
Effect.flatMap((registry) => registry.removeRoute(input.environmentId, input.routeId)),
|
||||
),
|
||||
});
|
||||
const reorderRoutes = createRuntimeCommand(runtime, {
|
||||
label: "environment-catalog:reorder-routes",
|
||||
scheduler: commandScheduler,
|
||||
concurrency: serial,
|
||||
execute: (input: {
|
||||
readonly environmentId: EnvironmentIdType;
|
||||
readonly routeIds: ReadonlyArray<string>;
|
||||
}) =>
|
||||
EnvironmentRegistry.EnvironmentRegistry.pipe(
|
||||
Effect.flatMap((registry) => registry.reorderRoutes(input.environmentId, input.routeIds)),
|
||||
),
|
||||
});
|
||||
const retryNow = createRuntimeCommand(runtime, {
|
||||
label: "environment-catalog:retry-now",
|
||||
scheduler: commandScheduler,
|
||||
@@ -181,6 +202,8 @@ export function createEnvironmentCatalogAtoms<R, E>(
|
||||
stateAtom,
|
||||
register,
|
||||
remove,
|
||||
removeRoute,
|
||||
reorderRoutes,
|
||||
removeRelayEnvironments,
|
||||
retryNow,
|
||||
setEnabled,
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type EnvironmentPresentation,
|
||||
} from "../connection/presentation.ts";
|
||||
import type { EnvironmentCatalogState } from "./connections.ts";
|
||||
import { hasRelayRoute } from "../connection/routes.ts";
|
||||
|
||||
function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
|
||||
if (left.size !== right.size) {
|
||||
@@ -98,7 +99,7 @@ export function projectEnvironmentConnectionSummary(
|
||||
environmentId,
|
||||
environmentLabel: environment.entry.target.label,
|
||||
displayUrl: connectionCatalogDisplayUrl(environment.entry) ?? "",
|
||||
isRelayManaged: environment.entry.target._tag === "RelayConnectionTarget",
|
||||
isRelayManaged: hasRelayRoute(environment.entry),
|
||||
isEnabled: environment.entry.enabled,
|
||||
connectionState: environment.connection.phase,
|
||||
connectionError: environment.connection.error,
|
||||
|
||||
@@ -132,6 +132,8 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?
|
||||
registerPlatform: () => Effect.die("Unexpected environment registration"),
|
||||
reconcilePlatform: () => Effect.die("Unexpected environment reconciliation"),
|
||||
remove: () => Effect.die("Unexpected environment removal"),
|
||||
removeRoute: () => Effect.die("Unexpected route removal"),
|
||||
reorderRoutes: () => Effect.die("Unexpected route reorder"),
|
||||
removeRelayEnvironments: () => Effect.die("Unexpected environment removal"),
|
||||
retryNow: () => Effect.void,
|
||||
setEnabled: () => Effect.die("Unexpected environment toggle"),
|
||||
|
||||
@@ -81,6 +81,19 @@ export const isLocalLoopbackHost = (host: string): boolean => {
|
||||
return parseIpv4Address(normalized)?.[0] === 127;
|
||||
};
|
||||
|
||||
/**
|
||||
* A Tailscale address: a MagicDNS name, the 100.64.0.0/10 range Tailscale
|
||||
* assigns, or its IPv6 range fd7a:115c:a1e0::/48.
|
||||
*/
|
||||
export const isTailnetHost = (host: string): boolean => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (normalized.endsWith(".ts.net")) return true;
|
||||
const parts = parseIpv4Address(normalized);
|
||||
if (parts !== null) return parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127;
|
||||
const ipv6 = parseIpv6Address(normalized);
|
||||
return ipv6 !== null && ipv6PrefixMatches(ipv6, [0xfd7a, 0x115c, 0xa1e0, 0, 0, 0, 0, 0], 48);
|
||||
};
|
||||
|
||||
export const isPrivateNetworkHost = (host: string): boolean => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (
|
||||
|
||||
Reference in new issue
Block a user