Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 6ebcddac0f Update mobile relay token boundary
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:13:36 +00:00
Cursor AgentandJulius Marminge d45cbde1cd Format managed relay Effect refactor
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:12:01 +00:00
Cursor AgentandJulius Marminge 6f2607445f Fix managed relay TestClock coverage
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:10:44 +00:00
Cursor AgentandJulius Marminge 327cc7d919 Refactor managed relay session to idiomatic Effect
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:08:46 +00:00
Illia Panasenko 28107e89c2 chore: remove AnnotatableFileDiff leftovers, rename file (#3488) 2026-06-21 20:31:26 -07:00
14 changed files with 517 additions and 652 deletions

No files matched your search

+10 -7
View File
@@ -104,13 +104,16 @@ const capabilitiesLayer = Layer.succeedContext(
}),
),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
});
}
return token;
return yield* Option.match(token, {
onNone: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
}),
),
onSome: Effect.succeed,
});
}),
}),
).pipe(
@@ -1,12 +1,17 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
ManagedRelay,
ManagedRelaySessionTokenReadError,
setManagedRelaySession,
} from "@t3tools/client-runtime/relay";
import {
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { type ReactNode, useEffect, useRef } from "react";
import { environmentCatalog } from "../../connection/catalog";
@@ -39,7 +44,11 @@ export function activateCloudRelayAccount(
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken: tokenProvider,
readClerkToken: () =>
Effect.tryPromise({
try: tokenProvider,
catch: (cause) => new ManagedRelaySessionTokenReadError({ cause }),
}).pipe(Effect.map(Option.fromNullOr)),
});
}
@@ -9,7 +9,6 @@ import {
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
@@ -121,45 +120,39 @@ class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()
},
) {}
class WaitForRetrySignal extends Schema.TaggedErrorClass<WaitForRetrySignal>()(
"WaitForRetrySignal",
{
description: Schema.String,
},
) {}
const isWaitForRetrySignal = Schema.is(WaitForRetrySignal);
const WAIT_FOR_RETRY_INTERVAL = Duration.millis(10);
const WAIT_FOR_DEFAULT_TIMEOUT = Duration.seconds(40);
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeout?: Duration.Input,
timeoutMs?: number,
): Effect.Effect<A, never>;
function waitFor<A, B extends A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => value is B,
description: string,
timeout?: Duration.Input,
timeoutMs?: number,
): Effect.Effect<B, never>;
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeout: Duration.Input = WAIT_FOR_DEFAULT_TIMEOUT,
timeoutMs = 40_000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`);
return read.pipe(
Effect.filterOrFail(predicate, () => new WaitForRetrySignal({ description })),
Effect.filterOrFail(predicate, () => RETRY_SIGNAL),
Effect.retry({
schedule: Schedule.spaced(WAIT_FOR_RETRY_INTERVAL),
while: isWaitForRetrySignal,
}),
Effect.timeoutOrElse({
duration: timeout,
orElse: () => Effect.fail(new WaitForTimeoutError({ description })),
schedule: retrySchedule,
times: maxRetries,
while: (error) => error === RETRY_SIGNAL,
}),
Effect.mapError((error) =>
error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
),
Effect.orDie,
);
}
@@ -192,11 +185,11 @@ export interface OrchestrationIntegrationHarness {
readonly waitForThread: (
threadId: string,
predicate: (thread: OrchestrationThread) => boolean,
timeout?: Duration.Input,
timeoutMs?: number,
) => Effect.Effect<OrchestrationThread, never>;
readonly waitForDomainEvent: (
predicate: (event: OrchestrationEvent) => boolean,
timeout?: Duration.Input,
timeoutMs?: number,
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
readonly waitForPendingApproval: (
requestId: string,
@@ -205,7 +198,7 @@ export interface OrchestrationIntegrationHarness {
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
}) => boolean,
timeout?: Duration.Input,
timeoutMs?: number,
) => Effect.Effect<
{
readonly status: "pending" | "resolved";
@@ -217,11 +210,11 @@ export interface OrchestrationIntegrationHarness {
readonly waitForReceipt: {
(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeout?: Duration.Input,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeout?: Duration.Input,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
};
readonly dispose: Effect.Effect<void, never>;
@@ -427,29 +420,29 @@ export const makeOrchestrationIntegrationHarness = (
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(Duration.millis(10));
yield* Effect.sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
predicate,
timeout,
timeoutMs,
) =>
waitFor(
snapshotQuery
.getSnapshot()
.pipe(
Effect.map((snapshot) =>
Option.fromUndefinedOr(snapshot.threads.find((thread) => thread.id === threadId)),
Effect.map(
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
),
),
(thread) => Option.isSome(thread) && predicate(thread.value),
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
`projected thread '${threadId}'`,
timeout,
).pipe(Effect.map(Option.getOrThrow));
timeoutMs,
) as Effect.Effect<OrchestrationThread, never>;
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
predicate,
timeout,
timeoutMs,
) =>
waitFor(
Stream.runCollect(engine.readEvents(0)).pipe(
@@ -457,49 +450,68 @@ export const makeOrchestrationIntegrationHarness = (
),
(events) => events.some(predicate),
"domain event",
timeout,
timeoutMs,
);
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
requestId,
predicate,
timeout,
timeoutMs,
) =>
waitFor(
pendingApprovalRepository
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
.pipe(
Effect.map(
Option.map((value) => ({
status: value.status,
decision: value.decision,
resolvedAt: value.resolvedAt,
})),
Effect.map((row) =>
Option.match(row, {
onNone: () => null,
onSome: (value) => ({
status: value.status,
decision: value.decision,
resolvedAt: value.resolvedAt,
}),
}),
),
),
(row) => Option.isSome(row) && predicate(row.value),
(
row,
): row is {
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
} => row !== null && predicate(row),
`pending approval '${requestId}'`,
timeout,
).pipe(Effect.map(Option.getOrThrow));
timeoutMs,
) as Effect.Effect<
{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
},
never
>;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeout?: Duration.Input,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeout?: Duration.Input,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeout?: Duration.Input,
timeoutMs?: number,
) {
const readMatchingReceipt = Ref.get(receiptHistory).pipe(
Effect.map((history) => Option.fromUndefinedOr(history.find(predicate))),
Effect.map((history) => history.find(predicate)),
);
return waitFor(readMatchingReceipt, Option.isSome, "runtime receipt", timeout).pipe(
Effect.map(Option.getOrThrow),
return waitFor(
readMatchingReceipt,
(receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
"runtime receipt",
timeoutMs,
);
}
@@ -1,4 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import { describe, expect, it } from "@effect/vitest";
import { vi } from "vite-plus/test";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -81,24 +81,21 @@ function makeHandle(input: {
describe("CloudManagedEndpointRuntime", () => {
it("classifies Cloudflare connection and warning output", () => {
assert.equal(
expect(
ManagedEndpointRuntime.classifyRelayClientOutput(
"2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
),
"connected",
);
assert.equal(
).toBe("connected");
expect(
ManagedEndpointRuntime.classifyRelayClientOutput(
"2026-06-17T02:00:00Z ERR Failed to serve tunnel connection",
),
"warning",
);
assert.equal(
).toBe("warning");
expect(
ManagedEndpointRuntime.classifyRelayClientOutput(
"2026-06-17T02:00:00Z INF Starting metrics server",
),
"debug",
);
).toBe("debug");
});
it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
@@ -126,65 +123,41 @@ describe("CloudManagedEndpointRuntime", () => {
);
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
yield* runtime.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token-1",
tunnelId: "tunnel-1",
tunnelName: "t3-code-env-1",
}),
);
yield* runtime.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token-1",
tunnelId: "tunnel-1",
tunnelName: "t3-code-env-1",
}),
);
yield* runtime.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token-2",
tunnelId: "tunnel-1",
tunnelName: "t3-code-env-1",
}),
);
const stopped = yield* runtime.applyConfig(Option.none());
yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token-1",
tunnelId: "tunnel-1",
tunnelName: "t3-code-env-1",
});
yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token-1",
tunnelId: "tunnel-1",
tunnelName: "t3-code-env-1",
});
yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token-2",
tunnelId: "tunnel-1",
tunnelName: "t3-code-env-1",
});
const stopped = yield* runtime.applyConfig(null);
assert.deepEqual(
spawned.map((command) => command.command),
["cloudflared", "cloudflared"],
);
assert.deepEqual(
spawned.map((command) => command.args),
[
["tunnel", "run"],
["tunnel", "run"],
],
);
assert.deepEqual(
spawned.map((command) => command.options.env?.TUNNEL_TOKEN),
["token-1", "token-2"],
);
assert.deepEqual(
spawned.map((command) => command.options.stdout),
["pipe", "pipe"],
);
assert.deepEqual(
spawned.map((command) => command.options.stderr),
["pipe", "pipe"],
);
assert.deepEqual(
spawned.map((command) => command.options.detached),
[false, false],
);
assert.deepEqual(
spawned.map((command) => command.options.shell),
[false, false],
);
assert.deepEqual(killed, [100, 101]);
assert.deepEqual(stopped, { status: "disabled" });
expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
expect(spawned.map((command) => command.args)).toEqual([
["tunnel", "run"],
["tunnel", "run"],
]);
expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
"token-1",
"token-2",
]);
expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
expect(killed).toEqual([100, 101]);
expect(stopped).toEqual({ status: "disabled" });
}),
);
@@ -205,22 +178,18 @@ describe("CloudManagedEndpointRuntime", () => {
);
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
const started = yield* runtime.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
}),
);
const unsupported = yield* runtime.applyConfig(
Option.some({
providerKind: "manual",
connectorToken: "manual-token",
}),
);
const started = yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
});
const unsupported = yield* runtime.applyConfig({
providerKind: "manual",
connectorToken: "manual-token",
});
assert.equal(started.status, "running");
assert.deepEqual(unsupported, { status: "unsupported", providerKind: "manual" });
assert.deepEqual(killed, [200]);
expect(started.status).toBe("running");
expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" });
expect(killed).toEqual([200]);
}),
);
@@ -251,20 +220,14 @@ describe("CloudManagedEndpointRuntime", () => {
tunnelId: "tunnel-1",
};
const first = yield* runtime.applyConfig(Option.some(config));
const first = yield* runtime.applyConfig(config);
firstRunning = false;
const second = yield* runtime.applyConfig(Option.some(config));
const second = yield* runtime.applyConfig(config);
if (first.status !== "running") {
assert.fail(`Expected first connector to be running, got ${first.status}`);
}
assert.equal(first.pid, 300);
if (second.status !== "running") {
assert.fail(`Expected second connector to be running, got ${second.status}`);
}
assert.equal(second.pid, 301);
assert.deepEqual(spawned, [300, 301]);
assert.deepEqual(killed, [300]);
expect(first).toMatchObject({ status: "running", pid: 300 });
expect(second).toMatchObject({ status: "running", pid: 301 });
expect(spawned).toEqual([300, 301]);
expect(killed).toEqual([300]);
}),
);
@@ -297,22 +260,17 @@ describe("CloudManagedEndpointRuntime", () => {
);
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
const started = yield* runtime.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
tunnelId: "tunnel-1",
}),
);
const started = yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
tunnelId: "tunnel-1",
});
yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
yield* Deferred.await(secondSpawned);
if (started.status !== "running") {
assert.fail(`Expected connector to be running, got ${started.status}`);
}
assert.equal(started.pid, 400);
assert.deepEqual(spawned, [400, 401]);
assert.deepEqual(killed, [400]);
expect(started).toMatchObject({ status: "running", pid: 400 });
expect(spawned).toEqual([400, 401]);
expect(killed).toEqual([400]);
}),
);
@@ -343,33 +301,26 @@ describe("CloudManagedEndpointRuntime", () => {
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
const first = yield* runtime
.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token-1",
}),
)
.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token-1",
})
.pipe(Effect.forkChild);
yield* Deferred.await(firstSpawnEntered);
const second = yield* runtime
.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token-2",
}),
)
.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token-2",
})
.pipe(Effect.forkChild);
yield* Deferred.succeed(releaseFirstSpawn, undefined);
yield* Fiber.join(first);
const status = yield* Fiber.join(second);
if (status.status !== "running") {
assert.fail(`Expected connector to be running, got ${status.status}`);
}
assert.equal(status.pid, 501);
assert.deepEqual(spawned, [500, 501]);
assert.deepEqual(killed, [500]);
expect(status).toMatchObject({ status: "running", pid: 501 });
expect(spawned).toEqual([500, 501]);
expect(killed).toEqual([500]);
}),
);
@@ -387,19 +338,17 @@ describe("CloudManagedEndpointRuntime", () => {
);
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
const status = yield* runtime.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
tunnelId: "tunnel-1",
}),
);
const status = yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
tunnelId: "tunnel-1",
});
if (status.status !== "failed") {
assert.fail(`Expected connector spawn to fail, got ${status.status}`);
}
assert.equal(status.providerKind, "cloudflare_tunnel");
assert.equal(status.tunnelId, "tunnel-1");
expect(status).toMatchObject({
status: "failed",
providerKind: "cloudflare_tunnel",
tunnelId: "tunnel-1",
});
}),
);
@@ -422,19 +371,17 @@ describe("CloudManagedEndpointRuntime", () => {
),
);
const status = yield* runtime.applyConfig(
Option.some({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
}),
);
const status = yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
});
assert.deepEqual(status, {
expect(status).toEqual({
status: "failed",
providerKind: "cloudflare_tunnel",
reason: "The relay client is not installed.",
});
assert.equal(spawn.mock.calls.length, 0);
expect(spawn).not.toHaveBeenCalled();
}),
);
});
+119 -134
View File
@@ -24,9 +24,9 @@ const readRuntimeConfig = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const bytes = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
if (Option.isNone(bytes)) {
return Option.none<RelayManagedEndpointRuntimeConfig>();
return null;
}
return decodeRuntimeConfig(bytesToString(bytes.value));
return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes.value)));
});
export type CloudManagedEndpointRuntimeStatus =
@@ -56,7 +56,7 @@ export class CloudManagedEndpointRuntime extends Context.Service<
CloudManagedEndpointRuntime,
{
readonly applyConfig: (
config: Option.Option<RelayManagedEndpointRuntimeConfig>,
config: RelayManagedEndpointRuntimeConfig | null,
) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;
}
>()("t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {}
@@ -84,32 +84,28 @@ function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
});
}
const stopConnector = (connector: Option.Option<ActiveConnector>) =>
Option.match(connector, {
onNone: () => Effect.void,
onSome: (active) =>
Scope.close(active.scope, Exit.void).pipe(
const stopConnector = (connector: ActiveConnector | null) =>
connector
? Scope.close(connector.scope, Exit.void).pipe(
Effect.tap(() =>
Effect.logInfo("Relay client stopped", {
pid: Number(active.child.pid),
pid: Number(connector.child.pid),
}),
),
Effect.ignore,
),
});
)
: Effect.void;
export const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const relayClient = yield* RelayClient.RelayClient;
const activeRef = yield* Ref.make<Option.Option<ActiveConnector>>(Option.none());
const desiredConfigRef = yield* Ref.make<Option.Option<RelayManagedEndpointRuntimeConfig>>(
Option.none(),
);
const activeRef = yield* Ref.make<ActiveConnector | null>(null);
const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
const reconcileSemaphore = yield* Semaphore.make(1);
let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];
const stopActive = Effect.gen(function* () {
const active = yield* Ref.getAndSet(activeRef, Option.none());
const active = yield* Ref.getAndSet(activeRef, null);
yield* stopConnector(active);
});
@@ -120,20 +116,19 @@ export const make = Effect.gen(function* () {
Effect.gen(function* () {
const active = yield* Ref.get(activeRef);
if (
Option.isNone(active) ||
active.value.child.pid !== connector.child.pid ||
active.value.configKey !== connector.configKey
active?.child.pid !== connector.child.pid ||
active.configKey !== connector.configKey
) {
return;
}
yield* Ref.set(activeRef, Option.none());
yield* stopConnector(Option.some(connector));
yield* Ref.set(activeRef, null);
yield* stopConnector(connector);
const desiredConfig = yield* Ref.get(desiredConfigRef);
if (
Option.isNone(desiredConfig) ||
desiredConfig.value.providerKind !== "cloudflare_tunnel" ||
runtimeConfigKey(desiredConfig.value) !== connector.configKey
!desiredConfig ||
desiredConfig.providerKind !== "cloudflare_tunnel" ||
runtimeConfigKey(desiredConfig) !== connector.configKey
) {
return;
}
@@ -186,130 +181,120 @@ export const make = Effect.gen(function* () {
),
);
reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(
function* (configOption) {
if (Option.isNone(configOption)) {
yield* stopActive;
return { status: "disabled" };
}
const config = configOption.value;
if (config.providerKind !== "cloudflare_tunnel") {
yield* stopActive;
return { status: "unsupported", providerKind: config.providerKind };
}
const nextConfigKey = runtimeConfigKey(config);
const active = yield* Ref.get(activeRef);
if (Option.isSome(active) && active.value.configKey === nextConfigKey) {
const isRunning = yield* active.value.child.isRunning.pipe(
Effect.orElseSucceed(() => false),
);
if (isRunning) {
return {
status: "running",
providerKind: "cloudflare_tunnel",
pid: Number(active.value.child.pid),
...(active.value.config.tunnelId ? { tunnelId: active.value.config.tunnelId } : {}),
...(active.value.config.tunnelName
? { tunnelName: active.value.config.tunnelName }
: {}),
} satisfies CloudManagedEndpointRuntimeStatus;
}
}
reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
if (!config || config.providerKind !== "cloudflare_tunnel") {
yield* stopActive;
return config
? { status: "unsupported", providerKind: config.providerKind }
: { status: "disabled" };
}
const executable = yield* relayClient.resolve;
if (executable.status !== "available") {
return {
status: "failed",
providerKind: "cloudflare_tunnel",
reason:
executable.status === "unsupported"
? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
: "The relay client is not installed.",
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
} satisfies CloudManagedEndpointRuntimeStatus;
}
const connectorScope = yield* Scope.make("sequential");
const child = yield* spawner
.spawn(
ChildProcess.make(executable.executablePath, ["tunnel", "run"], {
detached: false,
env: {
...process.env,
TUNNEL_TOKEN: config.connectorToken,
},
shell: false,
stderr: "pipe",
stdout: "pipe",
}),
)
.pipe(
Effect.provideService(Scope.Scope, connectorScope),
Effect.tap((child) =>
Effect.logInfo("Relay client process started; waiting for tunnel connection", {
pid: Number(child.pid),
tunnelId: config.tunnelId,
tunnelName: config.tunnelName,
}),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to start relay client", {
cause,
tunnelId: config.tunnelId,
tunnelName: config.tunnelName,
}).pipe(
Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
Effect.as({
status: "failed",
providerKind: "cloudflare_tunnel",
reason: String(cause),
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
} satisfies CloudManagedEndpointRuntimeStatus),
),
),
);
if ("status" in child && child.status === "failed") {
return child;
}
if (!("status" in child)) {
const connector = {
child,
scope: connectorScope,
configKey: nextConfigKey,
config,
} satisfies ActiveConnector;
yield* Ref.set(activeRef, Option.some(connector));
yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
yield* Effect.forkIn(superviseConnector(connector), connectorScope);
const nextConfigKey = runtimeConfigKey(config);
const active = yield* Ref.get(activeRef);
if (active?.configKey === nextConfigKey) {
const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
if (isRunning) {
return {
status: "running",
providerKind: "cloudflare_tunnel",
pid: Number(child.pid),
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
pid: Number(active.child.pid),
...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),
...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),
} satisfies CloudManagedEndpointRuntimeStatus;
}
}
yield* stopActive;
const executable = yield* relayClient.resolve;
if (executable.status !== "available") {
return {
status: "failed",
providerKind: "cloudflare_tunnel",
reason: "Relay client did not start.",
reason:
executable.status === "unsupported"
? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
: "The relay client is not installed.",
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
} satisfies CloudManagedEndpointRuntimeStatus;
},
);
}
const connectorScope = yield* Scope.make("sequential");
const child = yield* spawner
.spawn(
ChildProcess.make(executable.executablePath, ["tunnel", "run"], {
detached: false,
env: {
...process.env,
TUNNEL_TOKEN: config.connectorToken,
},
shell: false,
stderr: "pipe",
stdout: "pipe",
}),
)
.pipe(
Effect.provideService(Scope.Scope, connectorScope),
Effect.tap((child) =>
Effect.logInfo("Relay client process started; waiting for tunnel connection", {
pid: Number(child.pid),
tunnelId: config.tunnelId,
tunnelName: config.tunnelName,
}),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to start relay client", {
cause,
tunnelId: config.tunnelId,
tunnelName: config.tunnelName,
}).pipe(
Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
Effect.as({
status: "failed",
providerKind: "cloudflare_tunnel",
reason: String(cause),
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
} satisfies CloudManagedEndpointRuntimeStatus),
),
),
);
if ("status" in child && child.status === "failed") {
return child;
}
if (!("status" in child)) {
const connector = {
child,
scope: connectorScope,
configKey: nextConfigKey,
config,
} satisfies ActiveConnector;
yield* Ref.set(activeRef, connector);
yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
yield* Effect.forkIn(superviseConnector(connector), connectorScope);
return {
status: "running",
providerKind: "cloudflare_tunnel",
pid: Number(child.pid),
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
} satisfies CloudManagedEndpointRuntimeStatus;
}
return {
status: "failed",
providerKind: "cloudflare_tunnel",
reason: "Relay client did not start.",
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
} satisfies CloudManagedEndpointRuntimeStatus;
});
const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
(config: Option.Option<RelayManagedEndpointRuntimeConfig>) =>
(config: RelayManagedEndpointRuntimeConfig | null) =>
reconcileSemaphore.withPermits(1)(
Ref.set(desiredConfigRef, config).pipe(Effect.andThen(reconcileConfig(config))),
),
@@ -322,12 +307,12 @@ export const make = Effect.gen(function* () {
const initialConfig = yield* readRuntimeConfig.pipe(
Effect.catch((cause) =>
Effect.logWarning("Failed to read managed endpoint runtime config", { cause }).pipe(
Effect.as(Option.none<RelayManagedEndpointRuntimeConfig>()),
Effect.as(null),
),
),
);
yield* runtime.applyConfig(initialConfig);
yield* Effect.addFinalizer(() => runtime.applyConfig(Option.none()));
yield* Effect.addFinalizer(() => runtime.applyConfig(null));
return runtime;
});
+2 -2
View File
@@ -433,7 +433,7 @@ const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(fu
});
yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);
const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(
Option.fromNullOr(payload.endpointRuntime),
payload.endpointRuntime,
);
const ok =
endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
@@ -642,7 +642,7 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
function* (dependencies: CloudHttpDependencies) {
yield* requireEnvironmentScope(AuthRelayWriteScope);
const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(Option.none());
const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(null);
yield* Effect.all(
[
dependencies.secrets.remove(CLOUD_LINKED_USER_ID),
+4 -5
View File
@@ -2253,17 +2253,16 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
layers: {
cloudManagedEndpointRuntime: {
applyConfig: (config) => {
appliedRuntimeConfigs.push(Option.getOrNull(config));
if (Option.isNone(config)) {
appliedRuntimeConfigs.push(config);
if (!config) {
return Effect.succeed({ status: "disabled" });
}
const runtimeConfig = config.value;
return Effect.succeed({
status: "running",
providerKind: "cloudflare_tunnel",
pid: 123,
...(runtimeConfig.tunnelId ? { tunnelId: runtimeConfig.tunnelId } : {}),
...(runtimeConfig.tunnelName ? { tunnelName: runtimeConfig.tunnelName } : {}),
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
});
},
},
+3 -1
View File
@@ -1,4 +1,6 @@
import { managedRelaySessionAtom, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -45,7 +47,7 @@ describe("managed relay authentication", () => {
it("replaces an existing account session atomically", () => {
setManagedRelaySession(appAtomRegistry, {
accountId: "account-1",
readClerkToken: async () => "account-1-token",
readClerkToken: () => Effect.succeed(Option.some("account-1-token")),
});
activateManagedRelayAuthentication("account-2", async () => "account-2-token");
+11 -2
View File
@@ -1,11 +1,16 @@
import { useAuth } from "@clerk/react";
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
ManagedRelay,
ManagedRelaySessionTokenReadError,
setManagedRelaySession,
} from "@t3tools/client-runtime/relay";
import {
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { useEffect, useRef, type ReactNode } from "react";
import { environmentCatalog } from "../connection/catalog";
@@ -32,7 +37,11 @@ export function activateManagedRelayAuthentication(
relayTokenProvider = readClerkToken;
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken,
readClerkToken: () =>
Effect.tryPromise({
try: readClerkToken,
catch: (cause) => new ManagedRelaySessionTokenReadError({ cause }),
}).pipe(Effect.map(Option.fromNullOr)),
});
}
+1 -1
View File
@@ -38,7 +38,7 @@ import { resolveThreadRouteRef } from "../threadRoutes";
import { useClientSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableFileDiff";
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
import { Switch } from "./ui/switch";
import {
@@ -6,13 +6,7 @@ import type {
FileDiffMetadata,
SelectedLineRange,
} from "@pierre/diffs";
import {
CodeView,
type CodeViewHandle,
type CodeViewProps,
FileDiff,
type FileDiffProps,
} from "@pierre/diffs/react";
import { CodeView, type CodeViewHandle, type CodeViewProps } from "@pierre/diffs/react";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useMemo, useState, type ReactNode, type Ref } from "react";
@@ -76,178 +70,6 @@ function appendAnnotationEntry(
);
}
interface AnnotatableFileDiffProps {
fileDiff: FileDiffMetadata;
filePath: string;
sectionId: string;
sectionTitle: string;
composerDraftTarget: ScopedThreadRef | DraftId;
options: FileDiffProps<DiffCommentAnnotationGroup>["options"];
renderHeaderPrefix: (fileDiff: FileDiffMetadata) => ReactNode;
}
export function AnnotatableFileDiff({
fileDiff,
filePath,
sectionId,
sectionTitle,
composerDraftTarget,
options,
renderHeaderPrefix,
}: AnnotatableFileDiffProps) {
const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
const reviewComments = useComposerDraftStore(
(store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
);
const [selectedRange, setSelectedRange] = useState<SelectedLineRange | null>(null);
const [draftAnnotation, setDraftAnnotation] = useState<DiffCommentLineAnnotation | null>(null);
const persistedAnnotations = useMemo(
() =>
reviewComments
.filter(
(comment) =>
comment.sectionId === sectionId &&
comment.filePath === filePath &&
(comment.fenceLanguage ?? "diff") === "diff",
)
.reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
const range = restoreDiffReviewCommentRange(fileDiff, comment);
if (!range) return annotations;
return appendAnnotationEntry(annotations, range, {
id: comment.id,
kind: "comment",
range,
rangeLabel: comment.rangeLabel,
text: comment.text,
});
}, []),
[fileDiff, filePath, reviewComments, sectionId],
);
const lineAnnotations = useMemo(
() => (draftAnnotation ? [...persistedAnnotations, draftAnnotation] : persistedAnnotations),
[draftAnnotation, persistedAnnotations],
);
const removeAnnotationEntry = useCallback(
(entryId: string) => {
setSelectedRange(null);
if (
draftAnnotation?.metadata.entries.some(
(entry) => entry.id === entryId && entry.kind === "draft",
)
) {
setDraftAnnotation(null);
return;
}
removeReviewComment(composerDraftTarget, entryId);
},
[composerDraftTarget, draftAnnotation, removeReviewComment],
);
const submitAnnotationEntry = useCallback(
(entryId: string, text: string) => {
const entry = draftAnnotation?.metadata.entries.find((candidate) => candidate.id === entryId);
if (!entry) return;
const comment = buildDiffReviewComment({
id: entry.id,
sectionId,
sectionTitle,
filePath,
fileDiff,
range: entry.range,
text,
});
if (comment) {
addReviewComment(composerDraftTarget, comment);
}
setSelectedRange(null);
setDraftAnnotation(null);
},
[
addReviewComment,
composerDraftTarget,
fileDiff,
filePath,
draftAnnotation,
sectionId,
sectionTitle,
],
);
const beginComment = useCallback(
(range: SelectedLineRange) => {
const id = nextFileCommentId();
const comment = buildDiffReviewComment({
id,
sectionId,
sectionTitle,
filePath,
fileDiff,
range,
text: "",
});
if (!comment) return;
const draftEntry: DiffCommentAnnotationEntry = {
id,
kind: "draft",
range,
rangeLabel: comment.rangeLabel,
text: "",
};
setDraftAnnotation({
side: annotationSide(range),
lineNumber: range.end,
metadata: { entries: [draftEntry] },
});
},
[fileDiff, filePath, sectionId, sectionTitle],
);
const hasOpenCommentForm = draftAnnotation !== null;
const handleLineSelectionEnd = useCallback(
(range: SelectedLineRange | null) => {
setSelectedRange(range);
if (range) beginComment(range);
},
[beginComment],
);
return (
<FileDiff<DiffCommentAnnotationGroup>
fileDiff={fileDiff}
renderHeaderPrefix={renderHeaderPrefix}
options={{
...options,
enableGutterUtility: !hasOpenCommentForm,
enableLineSelection: !hasOpenCommentForm,
onGutterUtilityClick: setSelectedRange,
onLineSelectionChange: setSelectedRange,
onLineSelectionEnd: handleLineSelectionEnd,
}}
selectedLines={selectedRange}
lineAnnotations={lineAnnotations}
renderAnnotation={(annotation) => (
<div className="py-1">
{annotation.metadata.entries.map((entry) => (
<LocalCommentAnnotation
key={entry.id}
kind={entry.kind}
rangeLabel={entry.rangeLabel}
text={entry.text}
onCancel={() => removeAnnotationEntry(entry.id)}
onComment={(text) => submitAnnotationEntry(entry.id, text)}
onDelete={() => removeAnnotationEntry(entry.id)}
/>
))}
</div>
)}
/>
);
}
interface AnnotatableCodeViewProps {
files: ReadonlyArray<{
fileDiff: FileDiffMetadata;
+10 -7
View File
@@ -176,13 +176,16 @@ const capabilitiesLayer = Layer.effectContext(
}),
),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
});
}
return token;
return yield* Option.match(token, {
onNone: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
}),
),
onSome: Effect.succeed,
});
}),
});
const identity = RelayDeviceIdentity.of({
@@ -4,11 +4,15 @@ import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import { describe, expect, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, vi } from "vite-plus/test";
@@ -96,7 +100,7 @@ function createManager(
function setSession() {
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Promise.resolve("clerk-token"),
readClerkToken: () => Effect.succeed(Option.some("clerk-token")),
});
}
@@ -115,20 +119,17 @@ describe("createManagedRelayQueryManager", () => {
setSession();
expect(yield* Fiber.join(tokenFiber)).toBe("clerk-token");
expect(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size).toBe(0);
assert.equal(yield* Fiber.join(tokenFiber), "clerk-token");
assert.equal(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size, 0);
}),
);
it.effect("deduplicates concurrent Clerk token reads and reuses the token until JWT expiry", () =>
Effect.gen(function* () {
const token = clerkToken(4_102_444_800);
let resolveToken!: (value: string) => void;
const readClerkToken = vi.fn(
() =>
new Promise<string>((resolve) => {
resolveToken = resolve;
}),
const tokenDeferred = yield* Deferred.make<string>();
const readClerkToken = vi.fn(() =>
Deferred.await(tokenDeferred).pipe(Effect.map(Option.some)),
);
const session = createManagedRelaySession({
accountId: "account-1",
@@ -139,48 +140,69 @@ describe("createManagedRelayQueryManager", () => {
concurrency: "unbounded",
}).pipe(Effect.forkChild);
yield* Effect.yieldNow;
expect(readClerkToken).toHaveBeenCalledTimes(1);
assert.equal(readClerkToken.mock.calls.length, 1);
resolveToken(token);
expect(yield* Fiber.join(readsFiber)).toEqual([token, token]);
expect(yield* session.readClerkToken()).toBe(token);
expect(readClerkToken).toHaveBeenCalledTimes(1);
yield* Deferred.succeed(tokenDeferred, token);
assert.deepEqual(yield* Fiber.join(readsFiber), [Option.some(token), Option.some(token)]);
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), token);
assert.equal(readClerkToken.mock.calls.length, 1);
}),
);
it.effect("refreshes the cached Clerk token after JWT expiry using TestClock", () =>
Effect.gen(function* () {
const firstToken = clerkToken(10);
const secondToken = clerkToken(30);
const tokens = [firstToken, secondToken];
const readClerkToken = vi.fn(() =>
Effect.sync(() => Option.some(tokens.shift() ?? "unexpected-token")),
);
const session = createManagedRelaySession({
accountId: "account-1",
readClerkToken,
});
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), firstToken);
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), firstToken);
assert.equal(readClerkToken.mock.calls.length, 1);
yield* TestClock.adjust(Duration.seconds(6));
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), secondToken);
assert.equal(readClerkToken.mock.calls.length, 2);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("updates the token provider without replacing a same-account session", () =>
Effect.gen(function* () {
const firstRead = vi.fn(() => Promise.resolve<string | null>(null));
const firstRead = vi.fn(() => Effect.succeed(Option.none<string>()));
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: firstRead,
});
const firstSession = registry.get(managedRelaySessionAtom);
expect(firstSession).not.toBeNull();
expect(yield* firstSession!.readClerkToken()).toBeNull();
assert.isTrue(Option.isNone(yield* firstSession!.readClerkToken()));
const secondRead = vi.fn(() => Promise.resolve<string | null>("refreshed-token"));
const secondRead = vi.fn(() => Effect.succeed(Option.some("refreshed-token")));
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: secondRead,
});
expect(registry.get(managedRelaySessionAtom)).toBe(firstSession);
expect(yield* firstSession!.readClerkToken()).toBe("refreshed-token");
expect(firstRead).toHaveBeenCalledTimes(1);
expect(secondRead).toHaveBeenCalledTimes(1);
assert.equal(Option.getOrThrow(yield* firstSession!.readClerkToken()), "refreshed-token");
assert.equal(firstRead.mock.calls.length, 1);
assert.equal(secondRead.mock.calls.length, 1);
}),
);
it.effect("does not pin a refreshed session to an older pending token read", () =>
Effect.gen(function* () {
let resolveFirst!: (token: string) => void;
const firstTokenDeferred = yield* Deferred.make<string>();
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () =>
new Promise<string>((resolve) => {
resolveFirst = resolve;
}),
readClerkToken: () => Deferred.await(firstTokenDeferred).pipe(Effect.map(Option.some)),
});
const session = registry.get(managedRelaySessionAtom);
const firstRead = yield* session!.readClerkToken().pipe(Effect.forkChild);
@@ -188,19 +210,19 @@ describe("createManagedRelayQueryManager", () => {
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Promise.resolve("refreshed-token"),
readClerkToken: () => Effect.succeed(Option.some("refreshed-token")),
});
expect(yield* session!.readClerkToken()).toBe("refreshed-token");
resolveFirst("older-token");
expect(yield* Fiber.join(firstRead)).toBe("older-token");
assert.equal(Option.getOrThrow(yield* session!.readClerkToken()), "refreshed-token");
yield* Deferred.succeed(firstTokenDeferred, "older-token");
assert.equal(Option.getOrThrow(yield* Fiber.join(firstRead)), "older-token");
}),
);
it("emits credential changes only when the managed relay account changes", async () => {
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Promise.resolve("first-token"),
readClerkToken: () => Effect.succeed(Option.some("first-token")),
});
const changes = Effect.runPromise(
managedRelayAccountChanges(registry).pipe(Stream.take(2), Stream.runCollect),
@@ -211,11 +233,11 @@ describe("createManagedRelayQueryManager", () => {
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Promise.resolve("refreshed-token"),
readClerkToken: () => Effect.succeed(Option.some("refreshed-token")),
});
setManagedRelaySession(registry, {
accountId: "account-2",
readClerkToken: () => Promise.resolve("second-token"),
readClerkToken: () => Effect.succeed(Option.some("second-token")),
});
setManagedRelaySession(registry, null);
@@ -234,7 +256,7 @@ describe("createManagedRelayQueryManager", () => {
},
} satisfies RelayClientEnvironmentRecord;
const token = clerkToken(4_102_444_800);
const readClerkToken = vi.fn(() => Promise.resolve(token));
const readClerkToken = vi.fn(() => Effect.succeed(Option.some(token)));
const manager = createManager({
listEnvironments: () => Effect.succeed([environment, secondEnvironment]),
getEnvironmentStatus: ({ environmentId }) => {
@@ -9,27 +9,30 @@ import {
import { decodeRelayJwt } from "@t3tools/shared/relayJwt";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Data from "effect/Data";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { findErrorTraceId } from "../errors/errorTrace.ts";
import * as ManagedRelay from "./managedRelay.ts";
const DEFAULT_STALE_TIME_MS = 15_000;
const DEFAULT_IDLE_TTL_MS = 5 * 60_000;
const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000;
const DEFAULT_STALE_TIME = Duration.seconds(15);
const DEFAULT_IDLE_TTL = Duration.minutes(5);
const CLERK_TOKEN_EXPIRY_SKEW = Duration.seconds(5);
export interface ManagedRelaySession {
readonly accountId: string;
readonly readClerkToken: () => Effect.Effect<string | null, ManagedRelaySessionError>;
readonly readClerkToken: () => Effect.Effect<Option.Option<string>, ManagedRelaySessionError>;
}
export interface ManagedRelaySessionInput {
readonly accountId: string;
readonly readClerkToken: () => Promise<string | null>;
readonly readClerkToken: () => Effect.Effect<Option.Option<string>, ManagedRelaySessionError>;
}
interface ManagedRelaySessionControl {
@@ -55,14 +58,36 @@ export interface ManagedRelayQueryEvent {
readonly traceId?: string | null;
}
export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class ManagedRelaySessionTokenReadError extends Schema.TaggedErrorClass<ManagedRelaySessionTokenReadError>()(
"ManagedRelaySessionTokenReadError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not obtain the T3 Cloud session token.";
}
}
export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySnapshotError")<{
readonly message: string;
}> {}
export class ManagedRelaySessionTokenUnavailableError extends Schema.TaggedErrorClass<ManagedRelaySessionTokenUnavailableError>()(
"ManagedRelaySessionTokenUnavailableError",
{ reason: Schema.Literals(["missing-session", "missing-token"]) },
) {
override get message(): string {
return this.reason === "missing-session"
? "Sign in to T3 Cloud before loading relay data."
: "The T3 Cloud session token is unavailable.";
}
}
export const ManagedRelaySessionError = Schema.Union([
ManagedRelaySessionTokenReadError,
ManagedRelaySessionTokenUnavailableError,
]);
export type ManagedRelaySessionError = typeof ManagedRelaySessionError.Type;
export class ManagedRelaySnapshotError extends Schema.TaggedErrorClass<ManagedRelaySnapshotError>()(
"ManagedRelaySnapshotError",
{ message: Schema.String },
) {}
export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
Atom.keepAlive,
@@ -71,69 +96,102 @@ export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(nul
const managedRelaySessionControls = new WeakMap<ManagedRelaySession, ManagedRelaySessionControl>();
interface CachedClerkToken {
readonly token: string;
readonly expiresAtMillis: number;
}
interface PendingClerkTokenRead {
readonly deferred: Deferred.Deferred<Option.Option<string>, ManagedRelaySessionError>;
}
interface ManagedRelaySessionCacheState {
readonly readClerkToken: ManagedRelaySessionInput["readClerkToken"];
readonly generation: number;
readonly cachedToken: Option.Option<CachedClerkToken>;
readonly pendingToken: Option.Option<PendingClerkTokenRead>;
}
function isFreshCachedToken(cachedToken: CachedClerkToken, nowMillis: number): boolean {
return cachedToken.expiresAtMillis > nowMillis + Duration.toMillis(CLERK_TOKEN_EXPIRY_SKEW);
}
function decodeCachedToken(token: string): Option.Option<CachedClerkToken> {
try {
const expiresAtSeconds = decodeRelayJwt(token).exp;
return typeof expiresAtSeconds === "number"
? Option.some({ token, expiresAtMillis: expiresAtSeconds * 1_000 })
: Option.none();
} catch {
return Option.none();
}
}
export function createManagedRelaySession(input: ManagedRelaySessionInput): ManagedRelaySession {
let cachedToken: { readonly token: string; readonly expiresAtMillis: number } | null = null;
let pendingToken: Promise<string | null> | null = null;
let readClerkToken = input.readClerkToken;
let tokenProviderGeneration = 0;
const readCachedClerkToken = async (nowMillis: number): Promise<string | null> => {
if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) {
return cachedToken.token;
}
if (pendingToken) {
return await pendingToken;
}
const operationGeneration = tokenProviderGeneration;
const operation = readClerkToken().then((token) => {
if (operationGeneration !== tokenProviderGeneration) {
return token;
}
if (!token) {
cachedToken = null;
return null;
}
try {
const expiresAtSeconds = decodeRelayJwt(token).exp;
cachedToken =
typeof expiresAtSeconds === "number"
? { token, expiresAtMillis: expiresAtSeconds * 1_000 }
: null;
} catch {
cachedToken = null;
}
return token;
});
pendingToken = operation;
try {
return await operation;
} finally {
if (pendingToken === operation) {
pendingToken = null;
}
}
let state: ManagedRelaySessionCacheState = {
readClerkToken: input.readClerkToken,
generation: 0,
cachedToken: Option.none(),
pendingToken: Option.none(),
};
const session: ManagedRelaySession = {
accountId: input.accountId,
readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () {
const nowMillis = yield* Clock.currentTimeMillis;
return yield* Effect.tryPromise({
try: () => readCachedClerkToken(nowMillis),
catch: (cause) =>
new ManagedRelaySessionError({
message: "Could not obtain the T3 Cloud session token.",
cause,
}),
});
const current = state;
if (
Option.isSome(current.cachedToken) &&
isFreshCachedToken(current.cachedToken.value, nowMillis)
) {
return Option.some(current.cachedToken.value.token);
}
if (Option.isSome(current.pendingToken)) {
return yield* Deferred.await(current.pendingToken.value.deferred);
}
const deferred = yield* Deferred.make<Option.Option<string>, ManagedRelaySessionError>();
state = {
...state,
pendingToken: Option.some({ deferred }),
};
const readExit = yield* Effect.exit(current.readClerkToken());
if (Exit.isSuccess(readExit)) {
if (state.generation === current.generation) {
state = {
...state,
cachedToken: Option.isSome(readExit.value)
? decodeCachedToken(readExit.value.value)
: Option.none(),
};
}
yield* Deferred.succeed(deferred, readExit.value).pipe(Effect.orDie);
} else {
yield* Deferred.failCause(deferred, readExit.cause).pipe(Effect.orDie);
}
if (Option.isSome(state.pendingToken) && state.pendingToken.value.deferred === deferred) {
state = {
...state,
pendingToken: Option.none(),
};
}
if (Exit.isSuccess(readExit)) {
return readExit.value;
}
return yield* Effect.failCause(readExit.cause);
}),
};
managedRelaySessionControls.set(session, {
updateReadClerkToken: (nextReadClerkToken) => {
readClerkToken = nextReadClerkToken;
tokenProviderGeneration += 1;
pendingToken = null;
state = {
readClerkToken: nextReadClerkToken,
generation: state.generation + 1,
cachedToken: Option.none(),
pendingToken: Option.none(),
};
},
});
return session;
@@ -176,14 +234,12 @@ function readSessionClerkToken(
session: ManagedRelaySession,
): Effect.Effect<string, ManagedRelaySessionError> {
return session.readClerkToken().pipe(
Effect.flatMap((token) =>
token
? Effect.succeed(token)
: Effect.fail(
new ManagedRelaySessionError({
message: "The T3 Cloud session token is unavailable.",
}),
),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(new ManagedRelaySessionTokenUnavailableError({ reason: "missing-token" })),
onSome: Effect.succeed,
}),
),
);
}
@@ -224,11 +280,7 @@ function requireClerkToken(
): Effect.Effect<string, ManagedRelaySessionError> {
const session = get(managedRelaySessionAtom);
if (!session || session.accountId !== accountId) {
return Effect.fail(
new ManagedRelaySessionError({
message: "Sign in to T3 Cloud before loading relay data.",
}),
);
return Effect.fail(new ManagedRelaySessionTokenUnavailableError({ reason: "missing-session" }));
}
return readSessionClerkToken(session);
}
@@ -315,8 +367,8 @@ export function createManagedRelayQueryManager(
readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;
},
) {
const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
const staleTime = options?.staleTimeMs ?? Duration.toMillis(DEFAULT_STALE_TIME);
const idleTtl = options?.idleTtlMs ?? Duration.toMillis(DEFAULT_IDLE_TTL);
const observe = <A, E, R>(
input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
effect: Effect.Effect<A, E, R>,