refactor(server): T3 Connect link capabilities live in a CloudLink service (#16265)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-05 18:48:38 -07:00
1 parent ecfdda5fa8
commit 9422e2ee12
8 files changed
+1972 -1798

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schedule from "effect/Schedule";
import { CLOUD_REPLAY_MARKER_PREFIXES } from "../cloud/http.ts";
import { CLOUD_REPLAY_MARKER_PREFIXES } from "../cloud/CloudLink.ts";
import * as ServerConfig from "../config.ts";
import { forkParked } from "../serverActivation.ts";
import { DPOP_REPLAY_MARKER_PREFIX } from "./dpop.ts";
@@ -5,11 +5,18 @@ import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import { HttpClient, HttpServer } from "effect/http";
import * as NetAddress from "effect/net/NetAddress";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
import * as CloudPreferences from "./CloudPreferences.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import * as CloudLink from "./CloudLink.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import {
HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,
PUBLISH_AGENT_ACTIVITY_SECRET,
@@ -34,7 +41,7 @@ const withService = <A, E>(
};
},
body: (input: {
readonly preferences: CloudPreferences.CloudPreferences["Service"];
readonly preferences: { readonly update: CloudLink.CloudLink["Service"]["updatePreferences"] };
readonly stored: Map<string, Uint8Array>;
readonly relayCalls: Array<boolean>;
}) => Effect.Effect<A, E, never>,
@@ -88,12 +95,25 @@ const withService = <A, E>(
getEnvironmentId: Effect.succeed(EnvironmentId.make("environment-1")),
}),
Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ requestCatchUp: () => Effect.void }),
// Saving preferences touches none of the link's other dependencies.
Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),
Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
Layer.mock(HttpServer.HttpServer)({
address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
}),
Layer.mock(ServerConfig.ServerConfig)({} as ServerConfig.ServerConfig["Service"]),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unused")),
),
NodeServices.layer,
);
return yield* Effect.gen(function* () {
const preferences = yield* CloudPreferences.CloudPreferences;
return yield* body({ preferences, stored, relayCalls });
const link = yield* CloudLink.CloudLink;
return yield* body({ preferences: { update: link.updatePreferences }, stored, relayCalls });
}).pipe(
Effect.provide(CloudPreferences.layer.pipe(Layer.provide(layerDependencies))),
Effect.provide(CloudLink.layer.pipe(Layer.provide(layerDependencies))),
Effect.provideService(FetchHttpClient.Fetch, fetch),
);
});
File diff suppressed because it is too large. Load diff
-133
View File
@@ -1,133 +0,0 @@
import {
type EnvironmentCloudPreferencesRequest,
EnvironmentHttpBadRequestError,
EnvironmentHttpInternalServerError,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Semaphore from "effect/Semaphore";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
import { makeRelayEnvironmentClient } from "../relay/relayEnvironmentClient.ts";
import {
HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,
PUBLISH_AGENT_ACTIVITY_SECRET,
readRelayConnection,
} from "./config.ts";
const encode = (value: boolean) => new TextEncoder().encode(String(value));
/** A failed rollback leaves a setting changed; it is logged, not hidden. */
const rollbackFailed = (cause: unknown) =>
Effect.logWarning("Could not roll back a T3 Connect preference", { cause });
const internalError = (message: string) => (cause: unknown) =>
Effect.logError(message, { cause }).pipe(
Effect.andThen(Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
);
export class CloudPreferences extends Context.Service<
CloudPreferences,
{
/**
* Saves this environment's T3 Connect preferences, all or nothing. The
* activity setting is saved first. Holding webhooks while offline is decided
* by the relay, so the relay is told before the local copy is saved. If
* either step fails, the activity setting is put back, and so is the relay
* when only the local save failed.
*/
readonly update: (
input: EnvironmentCloudPreferencesRequest,
) => Effect.Effect<void, EnvironmentHttpBadRequestError | EnvironmentHttpInternalServerError>;
}
>()("t3/cloud/CloudPreferences") {}
const make = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const environment = yield* ServerEnvironment.ServerEnvironment;
const awarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
const withSecrets = Effect.provideService(ServerSecretStore.ServerSecretStore, secrets);
const pushHoldWebhooksWhileOffline = Effect.fn("CloudPreferences.pushHoldWebhooksWhileOffline")(
function* (holdWebhooksWhileOffline: boolean) {
const connection = yield* readRelayConnection.pipe(withSecrets);
if (connection === null) {
return yield* new EnvironmentHttpBadRequestError({
message: "Link this environment to T3 Connect first.",
});
}
const environmentId = yield* environment.getEnvironmentId;
const client = yield* makeRelayEnvironmentClient(connection);
yield* client.server
.updateLinkPreferences({
params: { environmentId },
payload: { holdWebhooksWhileOffline },
})
.pipe(
Effect.timeout("10 seconds"),
Effect.catch(internalError("Could not update T3 Connect webhook settings.")),
);
},
);
const save = (name: string, value: boolean) =>
secrets
.set(name, encode(value))
.pipe(Effect.catch(internalError("Could not persist environment cloud preferences.")));
// One update at a time, so two requests can't each leave one setting behind.
const updateLock = yield* Semaphore.make(1);
const update: CloudPreferences["Service"]["update"] = Effect.fn("CloudPreferences.update")(
function* (input) {
// All or nothing: the activity setting is saved first, before the relay
// is told anything, and put back if the hold change then fails. Both
// current values are read up front; a failed read stops here, before
// anything changes, because a guessed value would be the rollback target.
const readCurrent = (name: string) =>
secrets
.get(name)
.pipe(Effect.catch(internalError("Could not read environment cloud preferences.")));
const previousActivity = yield* readCurrent(PUBLISH_AGENT_ACTIVITY_SECRET);
const previousHold = yield* readCurrent(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET);
yield* save(PUBLISH_AGENT_ACTIVITY_SECRET, input.publishAgentActivity);
if (input.holdWebhooksWhileOffline !== undefined) {
const next = input.holdWebhooksWhileOffline;
const previous = Option.match(previousHold, {
onNone: () => false,
onSome: (bytes) => new TextDecoder().decode(bytes) === "true",
});
yield* pushHoldWebhooksWhileOffline(next).pipe(
Effect.andThen(
save(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET, next).pipe(
Effect.tapError(() =>
previous === next
? Effect.void
: pushHoldWebhooksWhileOffline(previous).pipe(Effect.catch(rollbackFailed)),
),
),
),
Effect.tapError(() =>
Option.match(previousActivity, {
onNone: () => secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),
onSome: (bytes) => secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, bytes),
}).pipe(Effect.catch(rollbackFailed)),
),
);
}
yield* awarenessRelay.requestCatchUp();
},
// A client that disconnects mid-update must not stop it between a save and
// its rollback, so an update always finishes or undoes itself.
Effect.uninterruptible,
updateLock.withPermits(1),
);
return CloudPreferences.of({ update });
});
export const layer = Layer.effect(CloudPreferences, make);
+35 -7
View File
@@ -16,9 +16,11 @@ import * as Stream from "effect/Stream";
import {
HttpClient,
HttpClientResponse,
HttpServer,
HttpServerRequest,
type HttpClientRequest,
} from "effect/http";
import * as NetAddress from "effect/net/NetAddress";
import { DESKTOP_UPDATE_RESTART_MARKER_FILE, EnvironmentId } from "@t3tools/contracts";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
@@ -49,19 +51,14 @@ import {
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_URL_SECRET,
} from "./config.ts";
import * as CloudLink from "./CloudLink.ts";
import {
consumeCloudReplayGuards,
isSupportedLinkProviderKind,
linkProofScopes,
pendingServiceUpdateExists,
parseManagedEndpointLocalOrigin,
reconcileDesiredCloudLink,
reconcileDesiredCloudLinkIfStillDesired,
recoverManagedCloudTunnel,
registerManagedCloudTunnelRecovery,
releaseManagedTunnelOnShutdown,
startManagedCloudTunnelIfOriginConfirmed,
} from "./http.ts";
} from "./CloudLink.ts";
import {
managedTunnelStartupAction,
retryManagedTunnelRegistration,
@@ -89,6 +86,29 @@ const idleAwarenessRelay = AgentAwarenessRelay.AgentAwarenessRelay.of({
requestCatchUp: () => Effect.void,
start: () => Effect.void,
});
// The connect routes register recovery against the listening port; these tests
// call the service directly.
const idleHttpServer = HttpServer.HttpServer.of({
address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
});
const reconcileDesiredCloudLink = (localOrigin: string) =>
CloudLink.CloudLink.use((link) => link.reconcileDesiredLink(localOrigin));
const reconcileDesiredCloudLinkIfStillDesired = (localOrigin: string) =>
CloudLink.CloudLink.use((link) => link.reconcileDesiredLinkIfStillDesired(localOrigin));
const recoverManagedCloudTunnel = (
...args: Parameters<CloudLink.CloudLink["Service"]["recoverManagedTunnel"]>
) => CloudLink.CloudLink.use((link) => link.recoverManagedTunnel(...args));
const registerManagedCloudTunnelRecovery = (
...args: Parameters<CloudLink.CloudLink["Service"]["registerManagedTunnelRecovery"]>
) => CloudLink.CloudLink.use((link) => link.registerManagedTunnelRecovery(...args));
const releaseManagedTunnelOnShutdown = () =>
CloudLink.CloudLink.use((link) => link.releaseManagedTunnelOnShutdown());
const startManagedCloudTunnelIfOriginConfirmed = (
...args: Parameters<CloudLink.CloudLink["Service"]["startManagedTunnelIfOriginConfirmed"]>
) => CloudLink.CloudLink.use((link) => link.startManagedTunnelIfOriginConfirmed(...args));
const decodeManagedTunnelRecoveryRegistration = Schema.decodeUnknownEffect(
Schema.fromJsonString(RelayManagedEndpointRecoveryRegistrationRequest),
);
@@ -232,6 +252,12 @@ describe("reconcileDesiredCloudLink", () => {
message: "Run `t3 connect link` to authorize this environment.",
});
}).pipe(
Effect.provide(CloudLink.layer),
Effect.provideService(HttpServer.HttpServer, idleHttpServer),
Effect.provideService(
ServerConfigModule.ServerConfig,
ServerConfigModule.ServerConfig.of({} as ServerConfigModule.ServerConfig["Service"]),
),
Effect.provideService(
ServerSecretStore.ServerSecretStore,
makeSecretStore(unusedSecretStoreOperation),
@@ -384,6 +410,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
(harness: ReleaseHarness) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.provide(CloudLink.layer),
Effect.provideService(HttpServer.HttpServer, idleHttpServer),
Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),
Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),
Effect.provideService(
File diff suppressed because it is too large. Load diff
+48 -51
View File
@@ -112,7 +112,6 @@ import * as ReplayMarkers from "./auth/replayMarkers.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as WebhookRoute from "./scheduledTasks/webhookRoute.ts";
import * as RelayDeliveryProof from "./scheduledTasks/RelayDeliveryProof.ts";
import * as CloudPreferences from "./cloud/CloudPreferences.ts";
import * as HeldHooksWaker from "./relay/HeldHooksWaker.ts";
import {
relayHookBaseUrl,
@@ -124,15 +123,8 @@ import {
RELAY_URL_SECRET,
} from "./cloud/config.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
pendingServiceUpdateExists,
reconcileDesiredCloudLinkIfStillDesired,
recoverManagedCloudTunnel,
registerManagedCloudTunnelRecovery,
startManagedCloudTunnelIfOriginConfirmed,
releaseManagedTunnelOnShutdown,
} from "./cloud/http.ts";
import * as CloudHttp from "./cloud/http.ts";
import * as CloudLink from "./cloud/CloudLink.ts";
import * as RelayTracing from "./cloud/relayTracing.ts";
import { shouldRetryCloudLink } from "./cloud/relayResponse.ts";
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
@@ -658,7 +650,7 @@ const layerMakeRoutes = Layer.mergeAll(
Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(AuthHttp.layer),
Layer.provide(CloudHttp.layer.pipe(Layer.provide(CloudPreferences.layer))),
Layer.provide(CloudHttp.layer),
Layer.provide(OrchestrationHttp.layer),
Layer.provide(PullRequestHttp.layer),
Layer.provide(ProjectHttp.layer),
@@ -802,7 +794,8 @@ const layerMakeServer = Layer.unwrap(
: Layer.empty;
const layerCloudDesiredLinkReconcile = Layer.effectDiscard(
Effect.gen(function* () {
const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
const cloudLink = yield* CloudLink.CloudLink;
const releaseManagedTunnel = cloudLink.releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
@@ -821,7 +814,7 @@ const layerMakeServer = Layer.unwrap(
// while the launcher's explicit-stop marker allows it to be released.
// Other runtimes wait for activation so a failed standby cannot tear
// down the active runtime's tunnel.
const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
const cleanupBeforeActivation = yield* CloudLink.pendingServiceUpdateExists;
if (cleanupBeforeActivation) {
yield* Effect.addFinalizer(() => releaseManagedTunnel);
}
@@ -846,7 +839,7 @@ const layerMakeServer = Layer.unwrap(
lastRecoveryAtMillis = yield* Clock.currentTimeMillis;
}).pipe(
Effect.andThen(
recoverManagedCloudTunnel(localOrigin, config, {
cloudLink.recoverManagedTunnel(localOrigin, config, {
retryRuntimeFailures: true,
}),
),
@@ -909,30 +902,32 @@ const layerMakeServer = Layer.unwrap(
const startedConfirmed =
desiredCliLinkMode === "publish_only"
? false
: yield* startManagedCloudTunnelIfOriginConfirmed(localOrigin).pipe(
: yield* cloudLink.startManagedTunnelIfOriginConfirmed(localOrigin).pipe(
Effect.catch((cause) =>
Effect.logWarning("Failed to start the confirmed T3 Connect tunnel", {
cause,
}).pipe(Effect.as(false)),
),
);
const startStoredManagedTunnel = startManagedCloudTunnelIfOriginConfirmed(localOrigin, {
requireConfirmedOrigin: false,
}).pipe(
Effect.tap((started) =>
started
? Effect.logWarning(
"T3 Connect started the stored tunnel without relay confirmation",
)
: Effect.void,
),
Effect.catch((cause) =>
Effect.logWarning("Failed to start the stored T3 Connect tunnel", { cause }),
),
Effect.asVoid,
);
const startStoredManagedTunnel = cloudLink
.startManagedTunnelIfOriginConfirmed(localOrigin, {
requireConfirmedOrigin: false,
})
.pipe(
Effect.tap((started) =>
started
? Effect.logWarning(
"T3 Connect started the stored tunnel without relay confirmation",
)
: Effect.void,
),
Effect.catch((cause) =>
Effect.logWarning("Failed to start the stored T3 Connect tunnel", { cause }),
),
Effect.asVoid,
);
const registerManagedTunnel = retryManagedTunnelRegistration(
registerManagedCloudTunnelRecovery(localOrigin, {
cloudLink.registerManagedTunnelRecovery(localOrigin, {
retryRuntimeFailures: true,
}),
(error) =>
@@ -978,29 +973,29 @@ const layerMakeServer = Layer.unwrap(
yield* endpointRuntime.requestRecovery(startupAction.config);
}
if (startupAction.action === "reconcile_link") {
const reconciledMode = yield* reconcileDesiredCloudLinkIfStillDesired(
localOrigin,
).pipe(
Effect.retry({
while: shouldRetryCloudLink,
schedule: Schedule.exponential("1 second").pipe(
Schedule.modifyDelay(({ duration }) =>
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
const reconciledMode = yield* cloudLink
.reconcileDesiredLinkIfStillDesired(localOrigin)
.pipe(
Effect.retry({
while: shouldRetryCloudLink,
schedule: Schedule.exponential("1 second").pipe(
Schedule.modifyDelay(({ duration }) =>
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
),
Schedule.upTo({ duration: "10 minutes" }),
),
Schedule.upTo({ duration: "10 minutes" }),
}),
Effect.tap((mode) =>
mode === null
? Effect.void
: Effect.logInfo("T3 Connect desired link reconciled on startup"),
),
}),
Effect.tap((mode) =>
mode === null
? Effect.void
: Effect.logInfo("T3 Connect desired link reconciled on startup"),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
cause,
}).pipe(Effect.as(null)),
),
);
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
cause,
}).pipe(Effect.as(null)),
),
);
if (reconciledMode === "managed") {
const afterReconcile = yield* registerManagedTunnel;
if (afterReconcile.status === "recovery_required") {
@@ -1045,6 +1040,8 @@ const layerMakeServer = Layer.unwrap(
);
return layerServerApplication.pipe(
// The connect routes and the startup/shutdown link work share one instance.
Layer.provide(CloudLink.layer),
Layer.provideMerge(layerRuntimeServices),
Layer.provideMerge(
McpSessionRegistry.layer.pipe(
+2 -2
View File
@@ -48,7 +48,7 @@ mint responses also bind the credential to the client proof key. The relay
verifies those bindings before returning a credential. This prevents a different
process behind the tunnel from impersonating the linked environment. The checks
meet in the
[environment cloud handlers](../../apps/server/src/cloud/http.ts) and
[environment link service](../../apps/server/src/cloud/CloudLink.ts) and
[relay connector](../../infra/relay/src/environments/EnvironmentConnector.ts).
The relay holds the signing authority for mint requests. DPoP protects an honest
@@ -80,7 +80,7 @@ Two cases must retain the tunnel across shutdown. A link installed through a
client has no startup provisioning path and depends on its stored connector
token. An update handoff immediately starts a replacement server, and replacing
the tunnel would add routing propagation delay to every update. These exceptions
belong to [shutdown handling](../../apps/server/src/cloud/http.ts).
belong to [shutdown handling](../../apps/server/src/cloud/CloudLink.ts).
Release and unlink claim the allocation generation before deleting external
resources. A delayed cleanup must not delete a tunnel reused by a concurrent