Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0909c502e | ||
|
|
0e4a43519f |
No files matched your search
@@ -10,3 +10,8 @@
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
# Public, ingest-only mobile OpenTelemetry configuration.
|
||||
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
|
||||
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
|
||||
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
|
||||
@@ -161,6 +161,11 @@ const config: ExpoConfig = {
|
||||
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
|
||||
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
|
||||
tracesToken: repoEnv.EXPO_PUBLIC_OTLP_TRACES_TOKEN ?? null,
|
||||
},
|
||||
eas: {
|
||||
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
|
||||
},
|
||||
|
||||
@@ -41,7 +41,7 @@ export function normalizeAgentAwarenessRelayBaseUrl(
|
||||
}
|
||||
|
||||
function readRelayConfig(): { readonly url: string } | null {
|
||||
const relayUrl = resolveCloudPublicConfig().relayUrl;
|
||||
const relayUrl = resolveCloudPublicConfig().relay.url;
|
||||
if (!relayUrl) {
|
||||
logRegistrationDebug("relay registration skipped; relay config missing");
|
||||
return null;
|
||||
|
||||
@@ -66,7 +66,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
}
|
||||
|
||||
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
|
||||
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
|
||||
const config = resolveCloudPublicConfig();
|
||||
const publishableKey = config.clerk.publishableKey;
|
||||
const relayUrl = config.relay.url;
|
||||
|
||||
useEffect(() => {
|
||||
if (!publishableKey || !relayUrl) {
|
||||
|
||||
@@ -50,7 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
|
||||
}
|
||||
|
||||
function readRelayUrl(): string | null {
|
||||
return resolveCloudPublicConfig().relayUrl;
|
||||
return resolveCloudPublicConfig().relay.url;
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
createManagedRelayQueryManager,
|
||||
ManagedRelayClient,
|
||||
managedRelaySessionAtom,
|
||||
readManagedRelaySnapshotState,
|
||||
} from "@t3tools/client-runtime";
|
||||
@@ -9,23 +8,13 @@ import type {
|
||||
RelayClientEnvironmentRecord,
|
||||
RelayEnvironmentStatusResponse,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { mobileRuntime } from "../../lib/runtime";
|
||||
import { mobileRuntimeContextLayer } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
|
||||
const managedRelayAtomRuntime = Atom.runtime(
|
||||
Layer.effect(
|
||||
ManagedRelayClient,
|
||||
mobileRuntime.contextEffect.pipe(
|
||||
Effect.map((context) => Context.get(context, ManagedRelayClient)),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
|
||||
|
||||
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { resolveCloudPublicConfig } from "./publicConfig";
|
||||
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
@@ -13,9 +13,18 @@ vi.mock("expo-constants", () => ({
|
||||
describe("resolveCloudPublicConfig", () => {
|
||||
it("returns no cloud configuration for an unconfigured build", () => {
|
||||
expect(resolveCloudPublicConfig({})).toEqual({
|
||||
clerkPublishableKey: null,
|
||||
clerkJwtTemplate: null,
|
||||
relayUrl: null,
|
||||
clerk: {
|
||||
publishableKey: null,
|
||||
jwtTemplate: null,
|
||||
},
|
||||
relay: {
|
||||
url: null,
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: null,
|
||||
tracesDataset: null,
|
||||
tracesToken: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,11 +33,25 @@ describe("resolveCloudPublicConfig", () => {
|
||||
resolveCloudPublicConfig({
|
||||
clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " },
|
||||
relay: { url: " https://relay.example.test/// " },
|
||||
observability: {
|
||||
tracesUrl: " https://api.axiom.co/v1/traces ",
|
||||
tracesDataset: " mobile-traces ",
|
||||
tracesToken: " public-ingest-token ",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
clerkPublishableKey: "pk_test_example",
|
||||
clerkJwtTemplate: "t3-relay",
|
||||
relayUrl: "https://relay.example.test",
|
||||
clerk: {
|
||||
publishableKey: "pk_test_example",
|
||||
jwtTemplate: "t3-relay",
|
||||
},
|
||||
relay: {
|
||||
url: "https://relay.example.test",
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -39,9 +62,59 @@ describe("resolveCloudPublicConfig", () => {
|
||||
relay: { url: "http://relay.example.test" },
|
||||
}),
|
||||
).toEqual({
|
||||
clerkPublishableKey: "pk_test_example",
|
||||
clerkJwtTemplate: "t3-relay",
|
||||
relayUrl: null,
|
||||
clerk: {
|
||||
publishableKey: "pk_test_example",
|
||||
jwtTemplate: "t3-relay",
|
||||
},
|
||||
relay: {
|
||||
url: null,
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: null,
|
||||
tracesDataset: null,
|
||||
tracesToken: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an insecure traces URL", () => {
|
||||
expect(
|
||||
resolveCloudPublicConfig({
|
||||
observability: {
|
||||
tracesUrl: "http://api.axiom.co/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
},
|
||||
}).observability,
|
||||
).toEqual({
|
||||
tracesUrl: null,
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps tracing disabled unless every public tracing value is configured", () => {
|
||||
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
|
||||
expect(
|
||||
hasMobileTracingPublicConfig(
|
||||
resolveCloudPublicConfig({
|
||||
observability: {
|
||||
tracesUrl: "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
hasMobileTracingPublicConfig(
|
||||
resolveCloudPublicConfig({
|
||||
observability: {
|
||||
tracesUrl: "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -2,40 +2,92 @@ import Constants from "expo-constants";
|
||||
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
|
||||
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
|
||||
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
|
||||
|
||||
export interface CloudPublicConfig {
|
||||
readonly clerkPublishableKey: string | null;
|
||||
readonly clerkJwtTemplate: string | null;
|
||||
readonly relayUrl: string | null;
|
||||
readonly clerk: {
|
||||
readonly publishableKey: string | null;
|
||||
readonly jwtTemplate: string | null;
|
||||
};
|
||||
readonly relay: {
|
||||
readonly url: string | null;
|
||||
};
|
||||
readonly observability: {
|
||||
readonly tracesUrl: string | null;
|
||||
readonly tracesDataset: string | null;
|
||||
readonly tracesToken: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
type UntrustedSection<T> = {
|
||||
readonly [Key in keyof T]?: unknown;
|
||||
};
|
||||
|
||||
type ExpoExtra =
|
||||
| {
|
||||
readonly [Section in keyof CloudPublicConfig]?: UntrustedSection<CloudPublicConfig[Section]>;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
function trimNonEmpty(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
|
||||
const clerk = extra?.clerk as
|
||||
| { readonly publishableKey?: unknown; readonly jwtTemplate?: unknown }
|
||||
| undefined;
|
||||
const relay = extra?.relay as { readonly url?: unknown } | undefined;
|
||||
function normalizeSecureUrl(value: unknown): string | null {
|
||||
const raw = trimNonEmpty(value);
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
return url.protocol === "https:" ? url.toString() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
|
||||
return {
|
||||
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
|
||||
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
|
||||
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
|
||||
clerk: {
|
||||
publishableKey: trimNonEmpty(extra?.clerk?.publishableKey),
|
||||
jwtTemplate: trimNonEmpty(extra?.clerk?.jwtTemplate),
|
||||
},
|
||||
relay: {
|
||||
url: normalizeSecureRelayUrl(trimNonEmpty(extra?.relay?.url) ?? ""),
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: normalizeSecureUrl(extra?.observability?.tracesUrl),
|
||||
tracesDataset: trimNonEmpty(extra?.observability?.tracesDataset),
|
||||
tracesToken: trimNonEmpty(extra?.observability?.tracesToken),
|
||||
},
|
||||
} satisfies CloudPublicConfig;
|
||||
}
|
||||
|
||||
export function hasCloudPublicConfig(): boolean {
|
||||
const config = resolveCloudPublicConfig();
|
||||
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
|
||||
return Boolean(config.clerk.publishableKey && config.clerk.jwtTemplate && config.relay.url);
|
||||
}
|
||||
|
||||
type Configured<T> = {
|
||||
readonly [Key in keyof T]: NonNullable<T[Key]>;
|
||||
};
|
||||
|
||||
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
|
||||
readonly observability: Configured<CloudPublicConfig["observability"]>;
|
||||
};
|
||||
|
||||
export function hasMobileTracingPublicConfig(
|
||||
config: CloudPublicConfig = resolveCloudPublicConfig(),
|
||||
): config is MobileTracingPublicConfig {
|
||||
return Boolean(
|
||||
config.observability.tracesUrl &&
|
||||
config.observability.tracesDataset &&
|
||||
config.observability.tracesToken,
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveRelayClerkTokenOptions() {
|
||||
const { clerkJwtTemplate } = resolveCloudPublicConfig();
|
||||
if (!clerkJwtTemplate) {
|
||||
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
|
||||
if (!jwtTemplate) {
|
||||
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
|
||||
}
|
||||
return relayClerkTokenOptions(clerkJwtTemplate);
|
||||
return relayClerkTokenOptions(jwtTemplate);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
|
||||
|
||||
import { makeMobileTracingLayer } from "./mobileTracing";
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
expoConfig: {
|
||||
extra: {},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
it.effect("exports spans through the scoped mobile OTLP layer", () => {
|
||||
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
|
||||
const tracingLayer = makeMobileTracingLayer(
|
||||
{
|
||||
tracesUrl: "https://api.axiom.test/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
},
|
||||
{
|
||||
appVariant: "test",
|
||||
serviceVersion: "1.2.3",
|
||||
},
|
||||
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
|
||||
const tracedApplication = Layer.effectDiscard(
|
||||
Effect.void.pipe(Effect.withSpan("mobile.test.span")),
|
||||
).pipe(Layer.provide(tracingLayer));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Layer.build(tracedApplication);
|
||||
|
||||
expect(fetchFn).not.toHaveBeenCalled();
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
expect(fetchFn).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetchFn.mock.calls[0]!;
|
||||
expect(String(url)).toBe("https://api.axiom.test/v1/traces");
|
||||
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");
|
||||
expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");
|
||||
expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import Constants from "expo-constants";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type { HttpClient } from "effect/unstable/http";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
|
||||
|
||||
export interface MobileTracingConfig {
|
||||
readonly tracesUrl: string;
|
||||
readonly tracesDataset: string;
|
||||
readonly tracesToken: string;
|
||||
}
|
||||
|
||||
export interface MobileTracingResource {
|
||||
readonly serviceVersion?: string;
|
||||
readonly appVariant: string;
|
||||
}
|
||||
|
||||
export function resolveMobileTracingConfig(): MobileTracingConfig | null {
|
||||
const config = resolveCloudPublicConfig();
|
||||
if (!hasMobileTracingPublicConfig(config)) {
|
||||
return null;
|
||||
}
|
||||
const { tracesUrl, tracesDataset, tracesToken } = config.observability;
|
||||
return { tracesUrl, tracesDataset, tracesToken };
|
||||
}
|
||||
|
||||
export function makeMobileTracingLayer(
|
||||
config: MobileTracingConfig | null,
|
||||
resource: MobileTracingResource,
|
||||
): Layer.Layer<never, never, HttpClient.HttpClient> {
|
||||
if (config === null) {
|
||||
return Layer.empty;
|
||||
}
|
||||
|
||||
return OtlpTracer.layer({
|
||||
url: config.tracesUrl,
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.tracesToken}`,
|
||||
"X-Axiom-Dataset": config.tracesDataset,
|
||||
},
|
||||
resource: {
|
||||
serviceName: "t3-mobile",
|
||||
serviceVersion: resource.serviceVersion,
|
||||
attributes: {
|
||||
"service.runtime": "react-native",
|
||||
"service.component": "mobile",
|
||||
"deployment.environment.name": resource.appVariant,
|
||||
},
|
||||
},
|
||||
}).pipe(Layer.provide(OtlpSerialization.layerJson));
|
||||
}
|
||||
|
||||
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), {
|
||||
serviceVersion: Constants.expoConfig?.version,
|
||||
appVariant:
|
||||
typeof Constants.expoConfig?.extra?.appVariant === "string"
|
||||
? Constants.expoConfig.extra.appVariant
|
||||
: "unknown",
|
||||
});
|
||||
@@ -6,19 +6,20 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime";
|
||||
import { mobileCryptoLayer } from "../features/cloud/dpop";
|
||||
import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer";
|
||||
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
|
||||
import { mobileTracingLayer } from "../features/observability/mobileTracing";
|
||||
|
||||
function configuredRelayUrl(): string {
|
||||
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
|
||||
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
|
||||
}
|
||||
|
||||
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
|
||||
|
||||
export const mobileRuntime = ManagedRuntime.make(
|
||||
Layer.mergeAll(
|
||||
mobileHttpClientLayer,
|
||||
mobileCryptoLayer,
|
||||
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
|
||||
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
|
||||
),
|
||||
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
|
||||
Layer.provideMerge(mobileCryptoLayer),
|
||||
Layer.provideMerge(mobileHttpClientLayer),
|
||||
Layer.provideMerge(mobileTracingLayer.pipe(Layer.provide(mobileHttpClientLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
export const mobileRuntimeContextLayer = Layer.effectContext(mobileRuntime.contextEffect);
|
||||
@@ -1,3 +1,4 @@
|
||||
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
|
||||
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -18,6 +19,7 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
const traceReferencesLayer = Layer.mergeAll(
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
|
||||
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
|
||||
httpHeaderRedactionLayer,
|
||||
);
|
||||
|
||||
const tracerLayer = Layer.unwrap(
|
||||
|
||||
@@ -284,11 +284,7 @@ interface SidebarThreadRowProps {
|
||||
isActive: boolean;
|
||||
jumpLabel: string | null;
|
||||
appSettingsConfirmThreadArchive: boolean;
|
||||
renamingThreadKey: string | null;
|
||||
renamingTitle: string;
|
||||
setRenamingTitle: (title: string) => void;
|
||||
renamingInputRef: React.RefObject<HTMLInputElement | null>;
|
||||
renamingCommittedRef: React.RefObject<boolean>;
|
||||
isRenaming: boolean;
|
||||
confirmingArchiveThreadKey: string | null;
|
||||
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
|
||||
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
|
||||
@@ -314,17 +310,77 @@ interface SidebarThreadRowProps {
|
||||
openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void;
|
||||
}
|
||||
|
||||
interface SidebarThreadRenameInputProps {
|
||||
thread: SidebarThreadSummary;
|
||||
threadRef: ScopedThreadRef;
|
||||
commitRename: (
|
||||
threadRef: ScopedThreadRef,
|
||||
newTitle: string,
|
||||
originalTitle: string,
|
||||
) => Promise<void>;
|
||||
cancelRename: () => void;
|
||||
}
|
||||
|
||||
const SidebarThreadRenameInput = memo(function SidebarThreadRenameInput({
|
||||
thread,
|
||||
threadRef,
|
||||
commitRename,
|
||||
cancelRename,
|
||||
}: SidebarThreadRenameInputProps) {
|
||||
const [title, setTitle] = useState(thread.title);
|
||||
const committedRef = useRef(false);
|
||||
const handleInputRef = useCallback((element: HTMLInputElement | null) => {
|
||||
if (!element) return;
|
||||
element.focus();
|
||||
element.select();
|
||||
}, []);
|
||||
const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setTitle(event.target.value);
|
||||
}, []);
|
||||
const handleKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
event.stopPropagation();
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
committedRef.current = true;
|
||||
void commitRename(threadRef, title, thread.title);
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
committedRef.current = true;
|
||||
cancelRename();
|
||||
}
|
||||
},
|
||||
[cancelRename, commitRename, thread.title, threadRef, title],
|
||||
);
|
||||
const handleBlur = useCallback(() => {
|
||||
if (!committedRef.current) {
|
||||
void commitRename(threadRef, title, thread.title);
|
||||
}
|
||||
}, [commitRename, thread.title, threadRef, title]);
|
||||
const handleClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
|
||||
event.stopPropagation();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<input
|
||||
ref={handleInputRef}
|
||||
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
|
||||
value={title}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onBlur={handleBlur}
|
||||
onClick={handleClick}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
|
||||
const {
|
||||
orderedProjectThreadKeys,
|
||||
isActive,
|
||||
jumpLabel,
|
||||
appSettingsConfirmThreadArchive,
|
||||
renamingThreadKey,
|
||||
renamingTitle,
|
||||
setRenamingTitle,
|
||||
renamingInputRef,
|
||||
renamingCommittedRef,
|
||||
isRenaming,
|
||||
confirmingArchiveThreadKey,
|
||||
setConfirmingArchiveThreadKey,
|
||||
confirmArchiveButtonRefs,
|
||||
@@ -454,45 +510,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
},
|
||||
[openPrLink, prStatus],
|
||||
);
|
||||
const handleRenameInputRef = useCallback(
|
||||
(element: HTMLInputElement | null) => {
|
||||
if (element && renamingInputRef.current !== element) {
|
||||
renamingInputRef.current = element;
|
||||
element.focus();
|
||||
element.select();
|
||||
}
|
||||
},
|
||||
[renamingInputRef],
|
||||
);
|
||||
const handleRenameInputChange = useCallback(
|
||||
(event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setRenamingTitle(event.target.value);
|
||||
},
|
||||
[setRenamingTitle],
|
||||
);
|
||||
const handleRenameInputKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
event.stopPropagation();
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
renamingCommittedRef.current = true;
|
||||
void commitRename(threadRef, renamingTitle, thread.title);
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
renamingCommittedRef.current = true;
|
||||
cancelRename();
|
||||
}
|
||||
},
|
||||
[cancelRename, commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef],
|
||||
);
|
||||
const handleRenameInputBlur = useCallback(() => {
|
||||
if (!renamingCommittedRef.current) {
|
||||
void commitRename(threadRef, renamingTitle, thread.title);
|
||||
}
|
||||
}, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]);
|
||||
const handleRenameInputClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
|
||||
event.stopPropagation();
|
||||
}, []);
|
||||
const handleConfirmArchiveRef = useCallback(
|
||||
(element: HTMLButtonElement | null) => {
|
||||
if (element) {
|
||||
@@ -578,15 +595,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
</Tooltip>
|
||||
)}
|
||||
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
|
||||
{renamingThreadKey === threadKey ? (
|
||||
<input
|
||||
ref={handleRenameInputRef}
|
||||
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
|
||||
value={renamingTitle}
|
||||
onChange={handleRenameInputChange}
|
||||
onKeyDown={handleRenameInputKeyDown}
|
||||
onBlur={handleRenameInputBlur}
|
||||
onClick={handleRenameInputClick}
|
||||
{isRenaming ? (
|
||||
<SidebarThreadRenameInput
|
||||
thread={thread}
|
||||
threadRef={threadRef}
|
||||
commitRename={commitRename}
|
||||
cancelRename={cancelRename}
|
||||
/>
|
||||
) : (
|
||||
<Tooltip>
|
||||
@@ -734,10 +748,6 @@ interface SidebarProjectThreadListProps {
|
||||
threadJumpLabelByKey: ReadonlyMap<string, string>;
|
||||
appSettingsConfirmThreadArchive: boolean;
|
||||
renamingThreadKey: string | null;
|
||||
renamingTitle: string;
|
||||
setRenamingTitle: (title: string) => void;
|
||||
renamingInputRef: React.RefObject<HTMLInputElement | null>;
|
||||
renamingCommittedRef: React.RefObject<boolean>;
|
||||
confirmingArchiveThreadKey: string | null;
|
||||
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
|
||||
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
|
||||
@@ -784,10 +794,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
|
||||
threadJumpLabelByKey,
|
||||
appSettingsConfirmThreadArchive,
|
||||
renamingThreadKey,
|
||||
renamingTitle,
|
||||
setRenamingTitle,
|
||||
renamingInputRef,
|
||||
renamingCommittedRef,
|
||||
confirmingArchiveThreadKey,
|
||||
setConfirmingArchiveThreadKey,
|
||||
confirmArchiveButtonRefs,
|
||||
@@ -834,11 +840,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
|
||||
isActive={activeRouteThreadKey === threadKey}
|
||||
jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null}
|
||||
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
|
||||
renamingThreadKey={renamingThreadKey}
|
||||
renamingTitle={renamingTitle}
|
||||
setRenamingTitle={setRenamingTitle}
|
||||
renamingInputRef={renamingInputRef}
|
||||
renamingCommittedRef={renamingCommittedRef}
|
||||
isRenaming={renamingThreadKey === threadKey}
|
||||
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
|
||||
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
|
||||
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
|
||||
@@ -1058,7 +1060,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
),
|
||||
);
|
||||
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
|
||||
const [renamingTitle, setRenamingTitle] = useState("");
|
||||
const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null);
|
||||
const [projectRenameTarget, setProjectRenameTarget] = useState<SidebarProjectGroupMember | null>(
|
||||
null,
|
||||
@@ -1069,8 +1070,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const [projectGroupingSelection, setProjectGroupingSelection] = useState<
|
||||
SidebarProjectGroupingMode | "inherit"
|
||||
>("inherit");
|
||||
const renamingCommittedRef = useRef(false);
|
||||
const renamingInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const memberProjectByScopedKey = useMemo(
|
||||
() =>
|
||||
@@ -1762,7 +1761,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const cancelRename = useCallback(() => {
|
||||
setRenamingThreadKey(null);
|
||||
renamingInputRef.current = null;
|
||||
}, []);
|
||||
|
||||
const commitRename = useCallback(
|
||||
@@ -1771,7 +1769,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const finishRename = () => {
|
||||
setRenamingThreadKey((current) => {
|
||||
if (current !== threadKey) return current;
|
||||
renamingInputRef.current = null;
|
||||
return null;
|
||||
});
|
||||
};
|
||||
@@ -1925,8 +1922,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
if (clicked === "rename") {
|
||||
setRenamingThreadKey(threadKey);
|
||||
setRenamingTitle(thread.title);
|
||||
renamingCommittedRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2088,10 +2083,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
threadJumpLabelByKey={threadJumpLabelByKey}
|
||||
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
|
||||
renamingThreadKey={renamingThreadKey}
|
||||
renamingTitle={renamingTitle}
|
||||
setRenamingTitle={setRenamingTitle}
|
||||
renamingInputRef={renamingInputRef}
|
||||
renamingCommittedRef={renamingCommittedRef}
|
||||
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
|
||||
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
|
||||
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Layer from "effect/Layer";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
|
||||
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
|
||||
import {
|
||||
PrimaryEnvironmentHttpClient,
|
||||
primaryEnvironmentHttpClientLive,
|
||||
@@ -28,6 +29,7 @@ const primaryHttpRuntime = ManagedRuntime.make(
|
||||
Layer.mergeAll(
|
||||
remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)),
|
||||
Layer.succeed(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit),
|
||||
httpHeaderRedactionLayer,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -8,6 +8,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Planetscale from "alchemy/Planetscale";
|
||||
|
||||
import { PlanetscaleDatabase, RelayHyperdrive } from "./src/db.ts";
|
||||
import { RelayObservability } from "./src/observability.ts";
|
||||
import { ManagedEndpointZone, RelayApiZone } from "./src/zone.ts";
|
||||
import Api from "./src/worker.ts";
|
||||
|
||||
@@ -27,6 +28,7 @@ export default Alchemy.Stack(
|
||||
const hyperdrive = yield* RelayHyperdrive;
|
||||
const managedEndpointZone = yield* ManagedEndpointZone.pipe(Effect.orDie);
|
||||
const relayApiZone = yield* RelayApiZone.pipe(Effect.orDie);
|
||||
const observability = yield* RelayObservability;
|
||||
const api = yield* Api;
|
||||
|
||||
return {
|
||||
@@ -37,6 +39,9 @@ export default Alchemy.Stack(
|
||||
url: api.url,
|
||||
relayApiZoneId: relayApiZone.zoneId,
|
||||
managedEndpointZoneId: managedEndpointZone.zoneId,
|
||||
mobileTracingUrl: observability.traces.otelTracesEndpoint,
|
||||
mobileTracingDataset: observability.traces.name,
|
||||
mobileTracingToken: observability.mobileIngestToken.token,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -1,6 +1,11 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { hasDeployChanges, reconcileRootEnvRelayUrl, serializeGithubOutput } from "./deploy.ts";
|
||||
import {
|
||||
hasDeployChanges,
|
||||
reconcileRootEnvPublicConfig,
|
||||
reconcileRootEnvRelayUrl,
|
||||
serializeGithubOutput,
|
||||
} from "./deploy.ts";
|
||||
|
||||
describe("hasDeployChanges", () => {
|
||||
it("detects resource, binding, and deletion changes", () => {
|
||||
@@ -51,6 +56,52 @@ describe("reconcileRootEnvRelayUrl", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileRootEnvPublicConfig", () => {
|
||||
const config = {
|
||||
relayUrl: "https://relay.example.test",
|
||||
mobileTracingUrl: "https://api.axiom.co/v1/traces",
|
||||
mobileTracingDataset: "t3-code-mobile-traces-dev",
|
||||
mobileTracingToken: "xaat-public-ingest",
|
||||
} as const;
|
||||
|
||||
it("adds the complete local client config", () => {
|
||||
expect(reconcileRootEnvPublicConfig("", config)).toBe(
|
||||
[
|
||||
"T3CODE_RELAY_URL=https://relay.example.test",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces stale values while preserving unrelated entries", () => {
|
||||
expect(
|
||||
reconcileRootEnvPublicConfig(
|
||||
[
|
||||
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example",
|
||||
"T3CODE_RELAY_URL=https://old.example.test",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_URL=https://old.example.test/v1/traces",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_DATASET=old-dataset",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=old-token",
|
||||
"",
|
||||
].join("\n"),
|
||||
config,
|
||||
),
|
||||
).toBe(
|
||||
[
|
||||
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example",
|
||||
"T3CODE_RELAY_URL=https://relay.example.test",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",
|
||||
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeGithubOutput", () => {
|
||||
it("serializes relay deploy metadata for GitHub Actions outputs", () => {
|
||||
expect(
|
||||
|
||||
@@ -23,6 +23,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import { Command, Flag, Prompt } from "effect/unstable/cli";
|
||||
import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
|
||||
|
||||
@@ -42,15 +43,49 @@ export interface RelayDeployOptions {
|
||||
readonly githubOutput: boolean;
|
||||
}
|
||||
|
||||
export interface RelayPublicConfig {
|
||||
readonly relayUrl: string;
|
||||
readonly mobileTracingUrl: string;
|
||||
readonly mobileTracingDataset: string;
|
||||
readonly mobileTracingToken: string;
|
||||
}
|
||||
|
||||
const publicConfigEnvEntries = (config: RelayPublicConfig) =>
|
||||
({
|
||||
T3CODE_RELAY_URL: config.relayUrl,
|
||||
T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileTracingUrl,
|
||||
T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileTracingDataset,
|
||||
T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileTracingToken,
|
||||
}) as const;
|
||||
|
||||
export function reconcileRootEnvPublicConfig(contents: string, config: RelayPublicConfig): string {
|
||||
let next = contents;
|
||||
for (const [name, value] of Object.entries(publicConfigEnvEntries(config))) {
|
||||
const entry = `${name}=${value}`;
|
||||
const pattern = new RegExp(`^${name}=.*$`, "mu");
|
||||
if (pattern.test(next)) {
|
||||
next = next.replace(pattern, entry);
|
||||
continue;
|
||||
}
|
||||
if (!next) {
|
||||
next = `${entry}\n`;
|
||||
continue;
|
||||
}
|
||||
next = `${next}${next.endsWith("\n") ? "" : "\n"}${entry}\n`;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function reconcileRootEnvRelayUrl(contents: string, relayUrl: string): string {
|
||||
const entry = `T3CODE_RELAY_URL=${relayUrl}`;
|
||||
if (/^T3CODE_RELAY_URL=.*$/mu.test(contents)) {
|
||||
return contents.replace(/^T3CODE_RELAY_URL=.*$/mu, entry);
|
||||
}
|
||||
if (!contents) {
|
||||
return `${entry}\n`;
|
||||
}
|
||||
return `${contents}${contents.endsWith("\n") ? "" : "\n"}${entry}\n`;
|
||||
return reconcileRootEnvPublicConfig(contents, {
|
||||
relayUrl,
|
||||
mobileTracingUrl: "",
|
||||
mobileTracingDataset: "",
|
||||
mobileTracingToken: "",
|
||||
})
|
||||
.split("\n")
|
||||
.filter((line) => !line.startsWith("T3CODE_MOBILE_OTLP_TRACES_"))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
export function hasDeployChanges(plan: Plan.Plan): boolean {
|
||||
@@ -68,7 +103,7 @@ export type RelayDeployResult = "applied" | "noop" | "dry-run" | "cancelled";
|
||||
export interface RelayDeployOutcome {
|
||||
readonly result: RelayDeployResult;
|
||||
readonly changed: boolean;
|
||||
readonly relayUrl: Option.Option<string>;
|
||||
readonly publicConfig: Option.Option<RelayPublicConfig>;
|
||||
}
|
||||
|
||||
export function serializeGithubOutput(entries: Readonly<Record<string, string | boolean>>): string {
|
||||
@@ -106,15 +141,17 @@ const relayDeployStage = Config.nonEmptyString("stage").pipe(
|
||||
),
|
||||
);
|
||||
|
||||
const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (relayUrl: string) {
|
||||
const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (
|
||||
config: RelayPublicConfig,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* repoRoot;
|
||||
const rootEnvPath = path.join(root, ".env");
|
||||
const contents = (yield* fs.exists(rootEnvPath)) ? yield* fs.readFileString(rootEnvPath) : "";
|
||||
|
||||
yield* fs.writeFileString(rootEnvPath, reconcileRootEnvRelayUrl(contents, relayUrl));
|
||||
yield* Console.log(`Updated ${rootEnvPath} with T3CODE_RELAY_URL=${relayUrl}`);
|
||||
yield* fs.writeFileString(rootEnvPath, reconcileRootEnvPublicConfig(contents, config));
|
||||
yield* Console.log(`Updated ${rootEnvPath} with relay URL and mobile tracing configuration`);
|
||||
});
|
||||
|
||||
const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function* (
|
||||
@@ -127,7 +164,9 @@ const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function*
|
||||
serializeGithubOutput({
|
||||
changed: outcome.changed,
|
||||
result: outcome.result,
|
||||
...(Option.isSome(outcome.relayUrl) ? { relay_url: outcome.relayUrl.value } : {}),
|
||||
...(Option.isSome(outcome.publicConfig)
|
||||
? { relay_url: outcome.publicConfig.value.relayUrl }
|
||||
: {}),
|
||||
}),
|
||||
{ flag: "a" },
|
||||
);
|
||||
@@ -160,7 +199,7 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
|
||||
return {
|
||||
result: "dry-run",
|
||||
changed,
|
||||
relayUrl: Option.none<string>(),
|
||||
publicConfig: Option.none<RelayPublicConfig>(),
|
||||
} satisfies RelayDeployOutcome;
|
||||
}
|
||||
if (!options.yes && changed) {
|
||||
@@ -175,20 +214,30 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
|
||||
return {
|
||||
result: "cancelled",
|
||||
changed,
|
||||
relayUrl: Option.none<string>(),
|
||||
publicConfig: Option.none<RelayPublicConfig>(),
|
||||
} satisfies RelayDeployOutcome;
|
||||
}
|
||||
}
|
||||
const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));
|
||||
if (output.url === undefined) {
|
||||
if (
|
||||
output.url === undefined ||
|
||||
output.mobileTracingUrl === undefined ||
|
||||
output.mobileTracingDataset === undefined ||
|
||||
output.mobileTracingToken === undefined
|
||||
) {
|
||||
return yield* new RelayDeployError({
|
||||
message: "Alchemy relay deploy output did not include a URL",
|
||||
message: "Alchemy relay deploy output did not include complete public client config",
|
||||
});
|
||||
}
|
||||
return {
|
||||
result: changed ? "applied" : "noop",
|
||||
changed,
|
||||
relayUrl: Option.some(output.url),
|
||||
publicConfig: Option.some({
|
||||
relayUrl: output.url,
|
||||
mobileTracingUrl: output.mobileTracingUrl,
|
||||
mobileTracingDataset: output.mobileTracingDataset,
|
||||
mobileTracingToken: Redacted.value(output.mobileTracingToken),
|
||||
}),
|
||||
} satisfies RelayDeployOutcome;
|
||||
},
|
||||
(effect, options, configProvider, stage) =>
|
||||
@@ -216,8 +265,8 @@ export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployO
|
||||
);
|
||||
const stage = Option.getOrElse(options.stage, () => configuredStage);
|
||||
const outcome = yield* runRelayDeploy(options, configProvider, stage);
|
||||
if (Option.isSome(outcome.relayUrl)) {
|
||||
yield* reconcileRootEnv(outcome.relayUrl.value);
|
||||
if (Option.isSome(outcome.publicConfig)) {
|
||||
yield* reconcileRootEnv(outcome.publicConfig.value);
|
||||
}
|
||||
if (options.githubOutput) {
|
||||
yield* writeGithubOutput(outcome);
|
||||
|
||||
@@ -101,8 +101,13 @@ const make = Effect.gen(function* () {
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
"relay.operation": "replayForLiveActivityRegistration",
|
||||
});
|
||||
const activeStates = yield* rows.listForUser({ userId: input.userId });
|
||||
const targets = yield* liveActivities.listTargets({ userId: input.userId });
|
||||
const { activeStates, targets } = yield* Effect.all(
|
||||
{
|
||||
activeStates: rows.listForUser({ userId: input.userId }),
|
||||
targets: liveActivities.listTargets({ userId: input.userId }),
|
||||
},
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
const target = targets.find((row) => row.device_id === input.deviceId) ?? null;
|
||||
if (target === null) {
|
||||
return null;
|
||||
|
||||
@@ -63,6 +63,6 @@ export const RelayHyperdrive = Effect.gen(function* () {
|
||||
caching: {
|
||||
disabled: true,
|
||||
},
|
||||
originConnectionLimit: 5,
|
||||
originConnectionLimit: 20,
|
||||
});
|
||||
});
|
||||
@@ -14,11 +14,13 @@ import {
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { RELAY_HEALTH_RESPONSE_TYP, RELAY_MINT_RESPONSE_TYP } from "@t3tools/shared/relayJwt";
|
||||
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 Redacted from "effect/Redacted";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
@@ -225,6 +227,58 @@ function makeLinks(
|
||||
}
|
||||
|
||||
describe("EnvironmentConnector", () => {
|
||||
it.effect("loads the environment link and managed allocation concurrently", () =>
|
||||
Effect.gen(function* () {
|
||||
const started = yield* Ref.make(0);
|
||||
const bothStarted = yield* Deferred.make<void>();
|
||||
const release = yield* Deferred.make<void>();
|
||||
const waitForPeer = Effect.gen(function* () {
|
||||
const count = yield* Ref.updateAndGet(started, (value) => value + 1);
|
||||
if (count === 2) {
|
||||
yield* Deferred.succeed(bothStarted, undefined);
|
||||
}
|
||||
yield* Deferred.await(release);
|
||||
});
|
||||
const links = makeLinks();
|
||||
const allocations = makeAllocations();
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const healthRequest = decodeHealthRequestBody(requestBodyText(request));
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json(signHealthResponse(healthRequest), { status: 200 }),
|
||||
);
|
||||
});
|
||||
const status = Effect.gen(function* () {
|
||||
const connector = yield* EnvironmentConnector.EnvironmentConnector;
|
||||
return yield* connector.status({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test" as never,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
connectorTestLayer(execute, {
|
||||
links: {
|
||||
...links,
|
||||
getForUser: (input) => waitForPeer.pipe(Effect.andThen(links.getForUser(input))),
|
||||
},
|
||||
allocations: {
|
||||
...allocations,
|
||||
get: (input) => waitForPeer.pipe(Effect.andThen(allocations.get(input))),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const fiber = yield* Effect.forkChild(status);
|
||||
yield* Deferred.await(bothStarted);
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
yield* Fiber.join(fiber);
|
||||
|
||||
expect(yield* Ref.get(started)).toBe(2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("checks linked environment health through the managed endpoint", () => {
|
||||
const seenUrls: Array<string> = [];
|
||||
const seenProofs: Array<RelayCloudEnvironmentHealthProofPayload> = [];
|
||||
|
||||
@@ -295,9 +295,9 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
const resolveManagedEndpoint = Effect.fn("relay.environment_connector.resolve_managed_endpoint")(
|
||||
function* (input: {
|
||||
readonly userId: string;
|
||||
readonly operation: "connect" | "status";
|
||||
readonly link: EnvironmentLinks.RelayLinkedEnvironmentRecord;
|
||||
readonly allocation: ManagedEndpointAllocations.ManagedEndpointAllocation | null;
|
||||
}) {
|
||||
if (input.link.endpoint.providerKind !== "cloudflare_tunnel") {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
@@ -309,11 +309,7 @@ const make = Effect.gen(function* () {
|
||||
reason: "endpoint_provider_not_managed",
|
||||
});
|
||||
}
|
||||
const allocation = yield* allocations.get({
|
||||
userId: input.userId,
|
||||
environmentId: input.link.environmentId,
|
||||
});
|
||||
if (!allocation) {
|
||||
if (!input.allocation) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.link.environmentId,
|
||||
operation: input.operation,
|
||||
@@ -321,10 +317,10 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
const allocationAttributes = {
|
||||
"relay.authorization.allocation_hostname": allocation.hostname,
|
||||
"relay.authorization.allocation_has_ready_at": allocation.readyAt !== null,
|
||||
"relay.authorization.allocation_has_tunnel_id": allocation.tunnelId !== null,
|
||||
"relay.authorization.allocation_has_dns_record_id": allocation.dnsRecordId !== null,
|
||||
"relay.authorization.allocation_hostname": input.allocation.hostname,
|
||||
"relay.authorization.allocation_has_ready_at": input.allocation.readyAt !== null,
|
||||
"relay.authorization.allocation_has_tunnel_id": input.allocation.tunnelId !== null,
|
||||
"relay.authorization.allocation_has_dns_record_id": input.allocation.dnsRecordId !== null,
|
||||
} as const;
|
||||
if (!settings.managedEndpointBaseDomain) {
|
||||
yield* Effect.annotateCurrentSpan(allocationAttributes);
|
||||
@@ -335,9 +331,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
if (
|
||||
allocation.readyAt === null ||
|
||||
allocation.tunnelId === null ||
|
||||
allocation.dnsRecordId === null
|
||||
input.allocation.readyAt === null ||
|
||||
input.allocation.tunnelId === null ||
|
||||
input.allocation.dnsRecordId === null
|
||||
) {
|
||||
yield* Effect.annotateCurrentSpan(allocationAttributes);
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
@@ -346,7 +342,9 @@ const make = Effect.gen(function* () {
|
||||
reason: "managed_endpoint_allocation_not_ready",
|
||||
});
|
||||
}
|
||||
if (!isManagedEndpointHostname(allocation.hostname, settings.managedEndpointBaseDomain)) {
|
||||
if (
|
||||
!isManagedEndpointHostname(input.allocation.hostname, settings.managedEndpointBaseDomain)
|
||||
) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
...allocationAttributes,
|
||||
"relay.authorization.managed_endpoint_base_domain": settings.managedEndpointBaseDomain,
|
||||
@@ -358,7 +356,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
const endpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({
|
||||
allocation,
|
||||
allocation: input.allocation,
|
||||
baseDomain: settings.managedEndpointBaseDomain,
|
||||
});
|
||||
if (
|
||||
@@ -393,7 +391,13 @@ const make = Effect.gen(function* () {
|
||||
"relay.environment_id": input.environmentId,
|
||||
"relay.operation": "status",
|
||||
});
|
||||
const link = yield* links.getForUser(input);
|
||||
const { link, allocation } = yield* Effect.all(
|
||||
{
|
||||
link: links.getForUser(input),
|
||||
allocation: allocations.get(input),
|
||||
},
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.environmentId,
|
||||
@@ -402,9 +406,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
const endpoint = yield* resolveManagedEndpoint({
|
||||
userId: input.userId,
|
||||
operation: "status",
|
||||
link,
|
||||
allocation,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
@@ -518,7 +522,13 @@ const make = Effect.gen(function* () {
|
||||
reason: "client_proof_key_thumbprint_missing",
|
||||
});
|
||||
}
|
||||
const link = yield* links.getForUser(input);
|
||||
const { link, allocation } = yield* Effect.all(
|
||||
{
|
||||
link: links.getForUser(input),
|
||||
allocation: allocations.get(input),
|
||||
},
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.environmentId,
|
||||
@@ -527,9 +537,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
const endpoint = yield* resolveManagedEndpoint({
|
||||
userId: input.userId,
|
||||
operation: "connect",
|
||||
link,
|
||||
allocation,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
|
||||
@@ -181,6 +181,10 @@ describe("relay request tracing", () => {
|
||||
const request = HttpServerRequest.fromWeb(
|
||||
new Request("https://relay.test/v1/mobile/devices?client=mobile", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: "Bearer secret",
|
||||
dpop: "signed-proof",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -192,6 +196,8 @@ describe("relay request tracing", () => {
|
||||
expect(spans[0]?.kind).toBe("server");
|
||||
expect(spans[0]?.attributes.get("url.path")).toBe("/v1/mobile/devices");
|
||||
expect(spans[0]?.attributes.get("http.response.status_code")).toBe(204);
|
||||
expect(spans[0]?.attributes.get("http.request.header.authorization")).toBe("<redacted>");
|
||||
expect(spans[0]?.attributes.get("http.request.header.dpop")).toBe("<redacted>");
|
||||
expect(Option.isNone(spans[0]!.parent)).toBe(true);
|
||||
expect(Option.getOrUndefined(spans[1]!.parent)?.spanId).toBe(spans[0]?.spanId);
|
||||
}),
|
||||
|
||||
+10
-13
@@ -3,6 +3,7 @@ import { sql as drizzleSql } from "drizzle-orm";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Record from "effect/Record";
|
||||
@@ -18,6 +19,7 @@ import * as HttpTraceContext from "effect/unstable/http/HttpTraceContext";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
|
||||
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
|
||||
|
||||
import {
|
||||
RelayApi,
|
||||
@@ -67,6 +69,7 @@ import { withSpanAttributes } from "../observability.ts";
|
||||
import { RelayDb } from "../db.ts";
|
||||
|
||||
const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const;
|
||||
const RELAY_DPOP_ACCESS_TOKEN_TTL = "30 minutes";
|
||||
const relayCorsAllowedHeaders = [
|
||||
"authorization",
|
||||
"b3",
|
||||
@@ -74,11 +77,7 @@ const relayCorsAllowedHeaders = [
|
||||
"content-type",
|
||||
"dpop",
|
||||
] as const;
|
||||
const relayCorsExposedHeaders = [
|
||||
"traceparent",
|
||||
"x-t3-relay-auth-failure",
|
||||
"www-authenticate",
|
||||
] as const;
|
||||
const relayCorsExposedHeaders = ["traceparent", "www-authenticate"] as const;
|
||||
|
||||
const relayCorsHeaders = {
|
||||
"access-control-allow-origin": "*",
|
||||
@@ -176,7 +175,10 @@ export const traceRelayHttpRequestWith = <E, R, LayerError, LayerRequirements>(
|
||||
HttpServerRequest.HttpServerRequest | R
|
||||
>,
|
||||
tracerLayer: Layer.Layer<never, LayerError, LayerRequirements>,
|
||||
) => traceRelayHttpRequest(httpEffect).pipe(Effect.provide(tracerLayer));
|
||||
) =>
|
||||
traceRelayHttpRequest(httpEffect).pipe(
|
||||
Effect.provide(Layer.merge(tracerLayer, httpHeaderRedactionLayer)),
|
||||
);
|
||||
|
||||
export const withoutCapturedParentSpan = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
@@ -351,12 +353,7 @@ export const healthApi = HttpApiBuilder.group(
|
||||
"health",
|
||||
Effect.fn("relay.api.health")(
|
||||
function* () {
|
||||
const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
|
||||
yield* db.execute(drizzleSql`SELECT 1`);
|
||||
const completedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
|
||||
yield* Effect.logInfo("relay health db probe completed", {
|
||||
durationMs: completedAt - startedAt,
|
||||
});
|
||||
return { ok: true, service: "relay" as const };
|
||||
},
|
||||
Effect.catch(() => relayInternalErrorResponse("database_unavailable")),
|
||||
@@ -602,7 +599,7 @@ export const tokenApi = HttpApiBuilder.group(
|
||||
Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 5 });
|
||||
const expiresAt = DateTime.addDuration(now, RELAY_DPOP_ACCESS_TOKEN_TTL);
|
||||
const jti = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.catch(() => relayInternalErrorResponse("internal_error")),
|
||||
);
|
||||
@@ -620,7 +617,7 @@ export const tokenApi = HttpApiBuilder.group(
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
|
||||
issued_token_type: RelayAccessTokenType,
|
||||
token_type: "DPoP" as const,
|
||||
expires_in: 300,
|
||||
expires_in: Duration.toSeconds(RELAY_DPOP_ACCESS_TOKEN_TTL),
|
||||
scope: encodeOAuthScope(requestedScopes),
|
||||
};
|
||||
}, mapRelayCommonApiErrors("invalid_dpop")),
|
||||
|
||||
@@ -34,7 +34,7 @@ export const RelayObservability = Effect.gen(function* () {
|
||||
useRetentionPeriod: true,
|
||||
});
|
||||
|
||||
const ingestToken = yield* Axiom.ApiToken("RelayAxiomIngestToken", {
|
||||
const workerIngestToken = yield* Axiom.ApiToken("RelayWorkerAxiomIngestToken", {
|
||||
name: relayResourceNameForStage("t3-code-relay-otel-ingest", stage),
|
||||
description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",
|
||||
datasetCapabilities: Output.map(traces.name, (dataset) => ({
|
||||
@@ -42,6 +42,14 @@ export const RelayObservability = Effect.gen(function* () {
|
||||
})),
|
||||
});
|
||||
|
||||
const mobileIngestToken = yield* Axiom.ApiToken("RelayMobileAxiomIngestToken", {
|
||||
name: relayResourceNameForStage("t3-code-mobile-otel-ingest", stage),
|
||||
description: "Owned by Alchemy. Scoped OTLP ingest token for T3 Code mobile spans.",
|
||||
datasetCapabilities: Output.map(traces.name, (dataset) => ({
|
||||
[dataset]: { ingest: ["create" as const] },
|
||||
})),
|
||||
});
|
||||
|
||||
yield* Axiom.View("RelayRecentSpansView", {
|
||||
name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),
|
||||
description: "Recent relay HTTP request spans.",
|
||||
@@ -49,7 +57,7 @@ export const RelayObservability = Effect.gen(function* () {
|
||||
aplQuery: Output.map(traces.name, relayRecentSpansQuery),
|
||||
});
|
||||
|
||||
return { traces, ingestToken } as const;
|
||||
return { traces, workerIngestToken, mobileIngestToken } as const;
|
||||
});
|
||||
|
||||
export const withSpanAttributes =
|
||||
|
||||
@@ -129,7 +129,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
const apnsDeliveryQueueSender = yield* Cloudflare.QueueBinding.bind(apnsDeliveryQueue);
|
||||
|
||||
const axiomDatasetName = yield* observability.traces.name;
|
||||
const axiomIngestToken = yield* observability.ingestToken.token;
|
||||
const axiomIngestToken = yield* observability.workerIngestToken.token;
|
||||
const axiomTracesEndpoint = yield* observability.traces.otelTracesEndpoint;
|
||||
|
||||
const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { definePlugin } from "@oxlint/plugins";
|
||||
|
||||
import noInlineSchemaCompile from "./rules/no-inline-schema-compile.ts";
|
||||
import noManualEffectRuntimeInTests from "./rules/no-manual-effect-runtime-in-tests.ts";
|
||||
|
||||
export default definePlugin({
|
||||
meta: {
|
||||
@@ -8,5 +9,6 @@ export default definePlugin({
|
||||
},
|
||||
rules: {
|
||||
"no-inline-schema-compile": noInlineSchemaCompile,
|
||||
"no-manual-effect-runtime-in-tests": noManualEffectRuntimeInTests,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { assert, describe } from "@effect/vitest";
|
||||
|
||||
import { createOxlintRuleHarness } from "../test/utils.ts";
|
||||
|
||||
const rule = createOxlintRuleHarness("t3code/no-manual-effect-runtime-in-tests", {
|
||||
filename: "fixture.test.ts",
|
||||
});
|
||||
|
||||
describe("t3code/no-manual-effect-runtime-in-tests", () => {
|
||||
rule.valid(
|
||||
"allows @effect/vitest effect tests",
|
||||
`
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
it.effect("runs an Effect", () => Effect.succeed("ok"));
|
||||
`,
|
||||
);
|
||||
|
||||
const runtimeMethods = [
|
||||
"runCallback",
|
||||
"runCallbackWith",
|
||||
"runFork",
|
||||
"runForkWith",
|
||||
"runPromise",
|
||||
"runPromiseExit",
|
||||
"runPromiseExitWith",
|
||||
"runPromiseWith",
|
||||
"runSync",
|
||||
"runSyncExit",
|
||||
"runSyncExitWith",
|
||||
"runSyncWith",
|
||||
] as const;
|
||||
|
||||
for (const method of runtimeMethods) {
|
||||
rule.invalid(
|
||||
`reports Effect.${method}`,
|
||||
`
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
test("runs an Effect", () => {
|
||||
Effect.${method}(Effect.succeed("ok"));
|
||||
});
|
||||
`,
|
||||
(output) => {
|
||||
assert.match(output, /Use @effect\/vitest with it\.effect/);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
rule.invalid(
|
||||
"reports ManagedRuntime.make",
|
||||
`
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
|
||||
test("makes a runtime", () => {
|
||||
ManagedRuntime.make(Layer.empty);
|
||||
});
|
||||
`,
|
||||
);
|
||||
});
|
||||
|
||||
const productionRule = createOxlintRuleHarness("t3code/no-manual-effect-runtime-in-tests");
|
||||
|
||||
productionRule.valid(
|
||||
"allows production runtime boundaries",
|
||||
`
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export const main = () => Effect.runPromise(Effect.void);
|
||||
`,
|
||||
);
|
||||
@@ -0,0 +1,113 @@
|
||||
import { defineRule } from "@oxlint/plugins";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { getPropertyName, isIdentifier, unwrapExpression } from "../utils.ts";
|
||||
|
||||
const TEST_FILE_PATTERN = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
|
||||
const EFFECT_RUNTIME_METHODS = new Set([
|
||||
"runCallback",
|
||||
"runCallbackWith",
|
||||
"runFork",
|
||||
"runForkWith",
|
||||
"runPromise",
|
||||
"runPromiseExit",
|
||||
"runPromiseExitWith",
|
||||
"runPromiseWith",
|
||||
"runSync",
|
||||
"runSyncExit",
|
||||
"runSyncExitWith",
|
||||
"runSyncWith",
|
||||
]);
|
||||
|
||||
// Existing manual runners are tracked as debt. The rule permits no net-new
|
||||
// occurrences in these files, while unlisted test files must have zero.
|
||||
const LEGACY_BASELINE = new Map<string, number>([
|
||||
["apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts", 1],
|
||||
["apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts", 2],
|
||||
["apps/mobile/src/state/use-remote-environment-registry.test.ts", 2],
|
||||
["apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts", 5],
|
||||
["apps/server/src/orchestration/commandInvariants.test.ts", 6],
|
||||
["apps/server/src/orchestration/Layers/CheckpointReactor.test.ts", 42],
|
||||
["apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts", 5],
|
||||
["apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts", 4],
|
||||
["apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts", 70],
|
||||
["apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts", 31],
|
||||
["apps/server/src/orchestration/Layers/ThreadDeletionReactor.test.ts", 2],
|
||||
["apps/server/src/orchestration/projector.test.ts", 20],
|
||||
["apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts", 4],
|
||||
["apps/server/src/provider/acp/CursorAcpSupport.test.ts", 1],
|
||||
["apps/server/src/provider/Layers/ClaudeAdapter.test.ts", 2],
|
||||
["apps/server/src/provider/Layers/CodexAdapter.test.ts", 1],
|
||||
["apps/server/src/provider/Layers/CodexSessionRuntime.test.ts", 5],
|
||||
["apps/server/src/provider/Layers/CursorAdapter.test.ts", 1],
|
||||
["apps/server/src/provider/Layers/CursorProvider.test.ts", 4],
|
||||
["apps/server/src/provider/Layers/ProviderService.test.ts", 2],
|
||||
["apps/server/src/provider/Layers/ProviderSessionReaper.test.ts", 21],
|
||||
["apps/server/src/relay/AgentAwarenessRelay.test.ts", 4],
|
||||
["apps/server/src/server.test.ts", 1],
|
||||
["apps/web/src/cloud/dpop.test.ts", 2],
|
||||
["apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts", 1],
|
||||
["oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.test.ts", 7],
|
||||
["packages/client-runtime/src/managedRelayState.test.ts", 1],
|
||||
["packages/client-runtime/src/wsTransport.test.ts", 2],
|
||||
]);
|
||||
|
||||
const baselineFor = (filename: string): number => {
|
||||
const normalized = filename.replaceAll("\\", "/");
|
||||
for (const [suffix, count] of LEGACY_BASELINE) {
|
||||
if (normalized.endsWith(suffix)) return count;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
const manualRunnerName = (callee: unknown): Option.Option<string> => {
|
||||
const expression = unwrapExpression(callee);
|
||||
if (Option.isNone(expression) || expression.value.type !== "MemberExpression") {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
const object = unwrapExpression(expression.value.object);
|
||||
const property = getPropertyName(expression.value.property);
|
||||
if (Option.isNone(property)) return Option.none();
|
||||
|
||||
if (isIdentifier(object, "Effect") && EFFECT_RUNTIME_METHODS.has(property.value)) {
|
||||
return Option.some(`Effect.${property.value}`);
|
||||
}
|
||||
|
||||
if (isIdentifier(object, "ManagedRuntime") && property.value === "make") {
|
||||
return Option.some("ManagedRuntime.make");
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
};
|
||||
|
||||
export default defineRule({
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Disallow manually creating or running Effect runtimes in tests; use @effect/vitest.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
if (!TEST_FILE_PATTERN.test(context.filename)) return {};
|
||||
|
||||
const allowedCount = baselineFor(context.filename);
|
||||
let occurrenceCount = 0;
|
||||
|
||||
return {
|
||||
CallExpression(node) {
|
||||
const runner = manualRunnerName(node.callee);
|
||||
if (Option.isNone(runner)) return;
|
||||
|
||||
occurrenceCount++;
|
||||
if (occurrenceCount <= allowedCount) return;
|
||||
|
||||
context.report({
|
||||
node: node.callee,
|
||||
message: `Do not use ${runner.value} in tests. Use @effect/vitest with it.effect(...) and test layers instead.`,
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -48,6 +48,10 @@ interface RuleHarness {
|
||||
readonly invalid: (name: string, source: string, assertion?: (output: string) => void) => void;
|
||||
}
|
||||
|
||||
interface RuleHarnessOptions {
|
||||
readonly filename?: string;
|
||||
}
|
||||
|
||||
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
@@ -73,7 +77,10 @@ const spawnAndCollectOutput = Effect.fnUntraced(function* (command: ChildProcess
|
||||
return { exitCode, stdout, stderr };
|
||||
}, Effect.scoped);
|
||||
|
||||
export const createOxlintRuleHarness = (ruleName: string): RuleHarness => {
|
||||
export const createOxlintRuleHarness = (
|
||||
ruleName: string,
|
||||
options: RuleHarnessOptions = {},
|
||||
): RuleHarness => {
|
||||
const [pluginName, shortRuleName] = ruleName.split("/");
|
||||
const diagnosticRuleName =
|
||||
pluginName && shortRuleName ? `${pluginName}\\(${shortRuleName}\\)` : ruleName;
|
||||
@@ -84,7 +91,7 @@ export const createOxlintRuleHarness = (ruleName: string): RuleHarness => {
|
||||
const path = yield* Path.Path;
|
||||
const fixtureDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-oxlint-" });
|
||||
const configPath = path.join(fixtureDir, ".oxlintrc.json");
|
||||
const sourcePath = path.join(fixtureDir, "fixture.ts");
|
||||
const sourcePath = path.join(fixtureDir, options.filename ?? "fixture.ts");
|
||||
const repoRoot = path.join(import.meta.dirname, "..", "..");
|
||||
const oxlintBin = path.join(
|
||||
repoRoot,
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
EnvironmentScopeRequiredError,
|
||||
} from "@t3tools/contracts";
|
||||
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -111,7 +112,10 @@ export type RemoteEnvironmentAuthError =
|
||||
export const remoteHttpClientLayer = (
|
||||
fetchFn: typeof globalThis.fetch,
|
||||
): Layer.Layer<HttpClient.HttpClient> =>
|
||||
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));
|
||||
Layer.merge(
|
||||
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
|
||||
httpHeaderRedactionLayer,
|
||||
);
|
||||
|
||||
const failRemoteRequest = (
|
||||
requestUrl: string,
|
||||
|
||||
@@ -31,6 +31,10 @@
|
||||
"types": "./src/observability.ts",
|
||||
"import": "./src/observability.ts"
|
||||
},
|
||||
"./httpObservability": {
|
||||
"types": "./src/httpObservability.ts",
|
||||
"import": "./src/httpObservability.ts"
|
||||
},
|
||||
"./shell": {
|
||||
"types": "./src/shell.ts",
|
||||
"import": "./src/shell.ts"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Headers from "effect/unstable/http/Headers";
|
||||
|
||||
export const httpHeaderRedactionLayer = Layer.effect(
|
||||
Headers.CurrentRedactedNames,
|
||||
Effect.map(Headers.CurrentRedactedNames, (names) => [...names, "dpop"]),
|
||||
);
|
||||
@@ -27,6 +27,12 @@ describe("loadRepoEnv", () => {
|
||||
expect(env.EXPO_PUBLIC_CLERK_JWT_TEMPLATE).toBeUndefined();
|
||||
expect(env.T3CODE_RELAY_URL).toBeUndefined();
|
||||
expect(env.VITE_T3CODE_RELAY_URL).toBeUndefined();
|
||||
expect(env.T3CODE_MOBILE_OTLP_TRACES_URL).toBeUndefined();
|
||||
expect(env.T3CODE_MOBILE_OTLP_TRACES_DATASET).toBeUndefined();
|
||||
expect(env.T3CODE_MOBILE_OTLP_TRACES_TOKEN).toBeUndefined();
|
||||
expect(env.EXPO_PUBLIC_OTLP_TRACES_URL).toBeUndefined();
|
||||
expect(env.EXPO_PUBLIC_OTLP_TRACES_DATASET).toBeUndefined();
|
||||
expect(env.EXPO_PUBLIC_OTLP_TRACES_TOKEN).toBeUndefined();
|
||||
});
|
||||
|
||||
it("applies process, root local, and root precedence in that order", () => {
|
||||
@@ -73,26 +79,41 @@ describe("loadRepoEnv", () => {
|
||||
VITE_CLERK_JWT_TEMPLATE: "template_legacy",
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_canonical",
|
||||
VITE_T3CODE_RELAY_URL: "https://legacy.example.test",
|
||||
EXPO_PUBLIC_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
|
||||
EXPO_PUBLIC_OTLP_TRACES_DATASET: "mobile-traces",
|
||||
EXPO_PUBLIC_OTLP_TRACES_TOKEN: "mobile-token",
|
||||
}),
|
||||
).toEqual({
|
||||
clerkPublishableKey: "pk_legacy",
|
||||
clerkJwtTemplate: "template_legacy",
|
||||
clerkCliOAuthClientId: "oauth_canonical",
|
||||
relayUrl: "https://legacy.example.test",
|
||||
mobileOtlpTracesUrl: "https://api.axiom.co/v1/traces",
|
||||
mobileOtlpTracesDataset: "mobile-traces",
|
||||
mobileOtlpTracesToken: "mobile-token",
|
||||
});
|
||||
});
|
||||
|
||||
it("projects only the configured aliases", () => {
|
||||
it("projects canonical mobile tracing values to Expo public aliases", () => {
|
||||
expect(
|
||||
loadRepoEnv({
|
||||
baseEnv: {
|
||||
T3CODE_RELAY_URL: "https://relay.example.test",
|
||||
T3CODE_MOBILE_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
|
||||
T3CODE_MOBILE_OTLP_TRACES_DATASET: "mobile-traces",
|
||||
T3CODE_MOBILE_OTLP_TRACES_TOKEN: "mobile-token",
|
||||
},
|
||||
repoRoot: makeTemporaryDirectory(),
|
||||
}),
|
||||
).toEqual({
|
||||
T3CODE_RELAY_URL: "https://relay.example.test",
|
||||
VITE_T3CODE_RELAY_URL: "https://relay.example.test",
|
||||
T3CODE_MOBILE_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
|
||||
T3CODE_MOBILE_OTLP_TRACES_DATASET: "mobile-traces",
|
||||
T3CODE_MOBILE_OTLP_TRACES_TOKEN: "mobile-token",
|
||||
EXPO_PUBLIC_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
|
||||
EXPO_PUBLIC_OTLP_TRACES_DATASET: "mobile-traces",
|
||||
EXPO_PUBLIC_OTLP_TRACES_TOKEN: "mobile-token",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,9 @@ export interface T3CodePublicConfig {
|
||||
readonly clerkJwtTemplate: string | undefined;
|
||||
readonly clerkCliOAuthClientId: string | undefined;
|
||||
readonly relayUrl: string | undefined;
|
||||
readonly mobileOtlpTracesUrl: string | undefined;
|
||||
readonly mobileOtlpTracesDataset: string | undefined;
|
||||
readonly mobileOtlpTracesToken: string | undefined;
|
||||
}
|
||||
|
||||
type Environment = Readonly<Record<string, string | undefined>>;
|
||||
@@ -57,6 +60,24 @@ export function loadRepoEnv({
|
||||
VITE_T3CODE_RELAY_URL: config.relayUrl,
|
||||
}
|
||||
: {}),
|
||||
...(config.mobileOtlpTracesUrl
|
||||
? {
|
||||
T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileOtlpTracesUrl,
|
||||
EXPO_PUBLIC_OTLP_TRACES_URL: config.mobileOtlpTracesUrl,
|
||||
}
|
||||
: {}),
|
||||
...(config.mobileOtlpTracesDataset
|
||||
? {
|
||||
T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileOtlpTracesDataset,
|
||||
EXPO_PUBLIC_OTLP_TRACES_DATASET: config.mobileOtlpTracesDataset,
|
||||
}
|
||||
: {}),
|
||||
...(config.mobileOtlpTracesToken
|
||||
? {
|
||||
T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileOtlpTracesToken,
|
||||
EXPO_PUBLIC_OTLP_TRACES_TOKEN: config.mobileOtlpTracesToken,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -76,6 +97,21 @@ export function resolvePublicConfig(...sources: readonly Environment[]): T3CodeP
|
||||
),
|
||||
clerkCliOAuthClientId: firstNonEmpty(sources, "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID"),
|
||||
relayUrl: firstNonEmpty(sources, "T3CODE_RELAY_URL", "VITE_T3CODE_RELAY_URL"),
|
||||
mobileOtlpTracesUrl: firstNonEmpty(
|
||||
sources,
|
||||
"T3CODE_MOBILE_OTLP_TRACES_URL",
|
||||
"EXPO_PUBLIC_OTLP_TRACES_URL",
|
||||
),
|
||||
mobileOtlpTracesDataset: firstNonEmpty(
|
||||
sources,
|
||||
"T3CODE_MOBILE_OTLP_TRACES_DATASET",
|
||||
"EXPO_PUBLIC_OTLP_TRACES_DATASET",
|
||||
),
|
||||
mobileOtlpTracesToken: firstNonEmpty(
|
||||
sources,
|
||||
"T3CODE_MOBILE_OTLP_TRACES_TOKEN",
|
||||
"EXPO_PUBLIC_OTLP_TRACES_TOKEN",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -91,6 +91,7 @@ export default defineConfig({
|
||||
"typescript/restrict-template-expressions": "off",
|
||||
"typescript/unbound-method": "off",
|
||||
"t3code/no-inline-schema-compile": "warn",
|
||||
"t3code/no-manual-effect-runtime-in-tests": "error",
|
||||
},
|
||||
options: {
|
||||
// Revisit once Oxlint's tsgolint path can integrate with @effect/tsgo diagnostics.
|
||||
|
||||
Reference in new issue
Block a user