Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/deploy-relay.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ jobs:
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
RELAY_MANAGED_ENDPOINT_PROVIDER: ${{ vars.RELAY_MANAGED_ENDPOINT_PROVIDER || 'cloudflare_tunnel' }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}
Expand Down
61 changes: 60 additions & 1 deletion apps/server/src/cloud/ManagedEndpointRuntime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import * as RelayClient from "@t3tools/shared/relayClient";

import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import * as T3RelayConnector from "./T3RelayConnector.ts";

const relayClientAvailableLayer = Layer.succeed(
RelayClient.RelayClient,
Expand Down Expand Up @@ -43,10 +44,11 @@ const runtimeDependencies = (
const buildCloudManagedEndpointRuntime = (
spawner: ReturnType<typeof ChildProcessSpawner.make>,
relayClientLayer = relayClientAvailableLayer,
t3RelayConnectorLayer = T3RelayConnector.layer,
) =>
Effect.gen(function* () {
const context = yield* Layer.build(
ManagedEndpointRuntime.layer.pipe(
ManagedEndpointRuntime.layerWithT3RelayConnectorFactory(t3RelayConnectorLayer).pipe(
Layer.provide(runtimeDependencies(spawner, relayClientLayer)),
),
);
Expand Down Expand Up @@ -202,6 +204,63 @@ describe("CloudManagedEndpointRuntime", () => {
}),
);

it.effect("starts, rotates, deduplicates, and stops the built-in T3 relay connector", () => {
const configs: Array<T3RelayConnector.T3RelayConnectorConfig> = [];
const closed: Array<number> = [];
const socket = (index: number): T3RelayConnector.RelayConnectorSocket => ({
binaryType: "arraybuffer",
readyState: 1,
send: () => undefined,
close: () => {
closed.push(index);
},
addEventListener: () => undefined,
});
const factoryLayer = Layer.succeed(
T3RelayConnector.T3RelayConnectorFactory,
T3RelayConnector.T3RelayConnectorFactory.of({
make: (config) => {
const index = configs.push(config);
return new T3RelayConnector.T3RelayConnectorSession(
config,
() => socket(index),
async () =>
Response.json({
ticket: `single-use-ticket-${index}`,
expiresAt: "2099-01-01T00:00:00.000Z",
}),
);
},
}),
);

return Effect.gen(function* () {
const runtime = yield* buildCloudManagedEndpointRuntime(
ChildProcessSpawner.make(() => Effect.die("unused")),
relayClientAvailableLayer,
factoryLayer,
);
const first = {
providerKind: "t3_relay" as const,
connectorToken: "token-1",
connectorUrl: "wss://env.edge.test/.well-known/t3-relay/connect",
originUrl: "http://127.0.0.1:7331",
};
expect(yield* runtime.applyConfig(first)).toEqual({
status: "running",
providerKind: "t3_relay",
});
yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
yield* runtime.applyConfig(first);
yield* runtime.applyConfig({ ...first, connectorToken: "token-2" });
yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
yield* runtime.applyConfig(null);

expect(configs.map((config) => config.connectorToken)).toEqual(["token-1", "token-2"]);
expect(closed).toEqual([1, 2]);
});
});

it.effect("restarts the connector when the active process has exited", () =>
Effect.gen(function* () {
const spawned: Array<number> = [];
Expand Down
90 changes: 89 additions & 1 deletion apps/server/src/cloud/ManagedEndpointRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne

import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { CLOUD_ENDPOINT_RUNTIME_CONFIG, decodeRuntimeConfig } from "./config.ts";
import * as T3RelayConnector from "./T3RelayConnector.ts";

function bytesToString(bytes: Uint8Array): string {
return new TextDecoder().decode(bytes);
Expand Down Expand Up @@ -47,6 +48,10 @@ export type CloudManagedEndpointRuntimeStatus =
readonly tunnelId?: string;
readonly tunnelName?: string;
}
| {
readonly status: "running";
readonly providerKind: "t3_relay";
}
| {
readonly status: "unsupported";
readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
Expand All @@ -68,6 +73,11 @@ interface ActiveConnector {
readonly config: RelayManagedEndpointRuntimeConfig;
}

interface ActiveT3Connector {
readonly session: T3RelayConnector.T3RelayConnectorSession;
readonly configKey: string;
}

export function classifyRelayClientOutput(line: string): "connected" | "warning" | "debug" {
if (/\bRegistered tunnel connection\b/iu.test(line)) {
return "connected";
Expand All @@ -82,6 +92,9 @@ function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
return JSON.stringify({
providerKind: config.providerKind,
connectorToken: config.connectorToken,
connectorLeaseId: config.connectorLeaseId ?? null,
connectorUrl: config.connectorUrl ?? null,
originUrl: config.originUrl ?? null,
tunnelId: config.tunnelId ?? null,
tunnelName: config.tunnelName ?? null,
});
Expand All @@ -100,18 +113,47 @@ const stopConnector = (connector: ActiveConnector | null) =>
: Effect.void;

export const make = Effect.gen(function* () {
const context = yield* Effect.context<never>();
const runFork = Effect.runForkWith(context);
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const relayClient = yield* RelayClient.RelayClient;
const t3RelayConnectorFactory = yield* T3RelayConnector.T3RelayConnectorFactory;
const activeRef = yield* Ref.make<ActiveConnector | null>(null);
const activeT3Ref = yield* Ref.make<ActiveT3Connector | null>(null);
const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
const reconcileSemaphore = yield* Semaphore.make(1);
let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];

const observeT3RelayConnector = (
event: T3RelayConnector.T3RelayConnectorLifecycleEvent,
): void => {
const log =
event.type === "connected"
? Effect.logInfo("T3 relay connector connected")
: event.type === "connecting"
? Effect.logDebug("T3 relay connector connecting")
: event.type === "disconnected"
? Effect.logWarning("T3 relay connector disconnected", {
code: event.code,
reason: event.reason,
})
: Effect.logWarning("T3 relay connector retry scheduled", {
attempt: event.attempt,
delayMillis: event.delayMillis,
reason: event.reason,
});
runFork(log);
};

const stopActive = Effect.gen(function* () {
const active = yield* Ref.getAndSet(activeRef, null);
yield* stopConnector(active);
});

const stopActiveT3 = Ref.getAndSet(activeT3Ref, null).pipe(
Effect.tap((active) => Effect.sync(() => active?.session.close())),
);

const superviseConnector = (connector: ActiveConnector) =>
Effect.gen(function* () {
const result = yield* Effect.result(connector.child.exitCode);
Expand Down Expand Up @@ -185,6 +227,48 @@ export const make = Effect.gen(function* () {
);

reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
if (config?.providerKind === "t3_relay") {
yield* stopActive;
const nextConfigKey = runtimeConfigKey(config);
const active = yield* Ref.get(activeT3Ref);
if (active?.configKey === nextConfigKey) {
return { status: "running", providerKind: "t3_relay" };
}
yield* stopActiveT3;
const connectorUrl = config.connectorUrl;
const originUrl = config.originUrl;
if (!connectorUrl || !originUrl) {
return {
status: "failed",
providerKind: "t3_relay",
reason: "The T3 relay connector URL or local origin is missing.",
};
}
const started = yield* Effect.try(() => {
const session = t3RelayConnectorFactory.make(
{
connectorUrl,
connectorToken: config.connectorToken,
originUrl,
},
observeT3RelayConnector,
);
session.start();
return session;
}).pipe(Effect.result);
if (Result.isFailure(started)) {
return {
status: "failed",
providerKind: "t3_relay",
reason: "Failed to start the T3 relay connector.",
};
}
const session = started.success;
yield* Ref.set(activeT3Ref, { session, configKey: nextConfigKey });
return { status: "running", providerKind: "t3_relay" };
}

yield* stopActiveT3;
if (!config || config.providerKind !== "cloudflare_tunnel") {
yield* stopActive;
return config
Expand Down Expand Up @@ -319,4 +403,8 @@ export const make = Effect.gen(function* () {
return runtime;
});

export const layer = Layer.effect(CloudManagedEndpointRuntime, make);
export const layerWithT3RelayConnectorFactory = (
factory: Layer.Layer<T3RelayConnector.T3RelayConnectorFactory>,
) => Layer.effect(CloudManagedEndpointRuntime, make).pipe(Layer.provide(factory));

export const layer = layerWithT3RelayConnectorFactory(T3RelayConnector.layer);
Loading
Loading