TypeScript
chore(relay): deploy with the Alchemy CLI and publish client config through an Action (#12401)
Julius Marminge747962568689
diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.ymlindex 25e744a4296..16e5c356219 100644--- a/.github/workflows/deploy-relay.yml+++ b/.github/workflows/deploy-relay.yml@@ -54,9 +54,11 @@ jobs:- --filter=t3code-relay...- name: Deploy production relay stage- id: deploy- run: vp run --filter t3code-relay deploy --stage prod --yes --github-output+ run: vp run --filter t3code-relay deploy --stage prod --yes --no-inputenv:+ # The PublishClientConfig action writes the client env here instead+ # of the repo-root .env; nothing on the runner reads it.+ T3CODE_RELAY_CLIENT_CONFIG_ENV: ${{ runner.temp }}/relay-client-config.envCLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}@@ -69,20 +71,12 @@ jobs:uses: actions/github-script@v8with:script: |- const result = "${{ steps.deploy.outputs.result }}";- const changed = "${{ steps.deploy.outputs.changed }}" === "true";- const description = changed- ? "Relay production deploy applied infrastructure changes."- : result === "noop"- ? "Relay production deploy was a no-op."- : `Relay production deploy completed with result: ${result}.`;-await github.rest.repos.createCommitStatus({owner: context.repo.owner,repo: context.repo.repo,sha: context.sha,state: "success",context: "Relay deploy / production",- description,+ description: "Relay production deploy completed.",target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,});diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex ae43abafd85..381a6b2b9b1 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -311,15 +311,28 @@ jobs:args:- --filter=t3code-relay...- - id: relay_state- name: Read production relay tracing config+ # The deployed stack's outputs, read from Alchemy's state store without+ # planning or applying. Redacted values are persisted as+ # {"__redacted__": "<value>"}; the token is masked before it is written.+ - name: Read production relay tracing configshell: bash+ working-directory: infra/relayrun: |- vp run --filter t3code-relay deploy \- --stage prod \- --read-state \- --github-output \- --github-env-file "$RUNNER_TEMP/relay-client-tracing.env"+ set -euo pipefail+ output="$(npx alchemy state read T3CodeRelay/prod/output --no-input)"+ field() {+ jq -er --arg key "$1" '.[$key] | if type == "object" then .__redacted__ else . end | select(. != null and . != "")' <<<"$output" \+ || { echo "Relay stack output is missing $1" >&2; exit 1; }+ }+ url="$(field clientTracingUrl)"+ dataset="$(field clientTracingDataset)"+ token="$(field clientTracingToken)"+ echo "::add-mask::$token"+ {+ echo "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=$url"+ echo "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=$dataset"+ echo "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=$token"+ } > "$RUNNER_TEMP/relay-client-tracing.env"- name: Upload relay client tracing configuses: actions/upload-artifact@v7diff --git a/docs/operations/connect-setup.md b/docs/operations/connect-setup.mdindex febc6f82e68..899d5c4a33a 100644--- a/docs/operations/connect-setup.md+++ b/docs/operations/connect-setup.md@@ -32,7 +32,7 @@ Bundled servers also accept runtime overrides for operator-managed deployments.Copy `infra/relay/.env.example` to `infra/relay/.env` for relay deployment settings.Deploy `prod` before personal stages because it owns the retained database that their branches-depend on. The deploy wrapper writes the resulting relay URL back to the root `.env`.+depend on. The stack's `PublishClientConfig` action writes the resulting relay URL back to the root `.env`.## CLI OAuth applicationdiff --git a/infra/relay/README.md b/infra/relay/README.mdindex 33bb0ba7435..350140c9b10 100644--- a/infra/relay/README.md+++ b/infra/relay/README.md@@ -76,7 +76,8 @@ dependencies represented at their boundary rather than mocking internal behavior## Deployment-The relay deploys through Alchemy:+The relay deploys with the Alchemy CLI (`vp run --filter t3code-relay deploy` is `alchemy deploy`+in this directory):```shvp run --filter t3code-relay deploy@@ -109,9 +110,10 @@ DNS-safe sanitization as Alchemy physical resource names, so `prod` uses`<stage>-<digest>.<RELAY_TUNNEL_ZONE_NAME>`. `RELAY_DOMAIN` remains available as an explicit APIdomain override.-After a successful deploy, the wrapper updates the repository-root `.env` file with the derived relay-URL. That makes subsequent source builds point at the relay that was just deployed without copying-the URL manually.+The stack's `PublishClientConfig` action ([`src/clientConfig.ts`](./src/clientConfig.ts)) writes the+deployed relay URL and tracing configuration into the repository-root `.env`, so subsequent source+builds point at the relay that was just deployed without copying values manually. It runs only when+one of those outputs changed, and `T3CODE_RELAY_CLIENT_CONFIG_ENV` redirects it to another file.### Deployment CIdiff --git a/infra/relay/alchemy.run.ts b/infra/relay/alchemy.run.tsindex 60f73bc3a76..bc40d4fe881 100644--- a/infra/relay/alchemy.run.ts+++ b/infra/relay/alchemy.run.ts@@ -1,5 +1,6 @@// @effect-diagnostics anyUnknownInErrorContext:off layerMergeAllWithDependencies:off - Alchemy provider helpers expose framework-owned any requirements.import * as Alchemy from "alchemy";+import * as Output from "alchemy/Output";import * as Axiom from "alchemy/Axiom";import * as Cloudflare from "alchemy/Cloudflare";import * as Drizzle from "alchemy/Drizzle";@@ -7,6 +8,7 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Planetscale from "alchemy/Planetscale";+import { PublishClientConfig, tokenDigest } from "./src/clientConfig.ts";import * as RelayDb from "./src/db.ts";import { RelayObservability } from "./src/observability.ts";import { ManagedEndpointZone, RelayApiZone } from "./src/zone.ts";@@ -30,6 +32,19 @@ export default Alchemy.Stack(const relayApiZone = yield* RelayApiZone.pipe(Effect.orDie);const observability = yield* RelayObservability;const api = yield* Api;+ yield* PublishClientConfig({+ url: api.url,+ mobileTracingUrl: observability.traces.otelTracesEndpoint,+ mobileTracingDataset: observability.traces.name,+ mobileTracingToken: observability.mobileIngestToken.token,+ clientTracingUrl: observability.traces.otelTracesEndpoint,+ clientTracingDataset: observability.traces.name,+ clientTracingToken: observability.clientIngestToken.token,+ tokenDigest: Output.map(+ Output.all(observability.mobileIngestToken.token, observability.clientIngestToken.token),+ tokenDigest,+ ),+ });return {databaseName: db.database.name,diff --git a/infra/relay/package.json b/infra/relay/package.jsonindex d00055ac620..02eecdfce21 100644--- a/infra/relay/package.json+++ b/infra/relay/package.json@@ -3,7 +3,7 @@"private": true,"type": "module","scripts": {- "deploy": "node -- scripts/deploy.ts",+ "deploy": "alchemy deploy","push:android:smoke": "node scripts/android-push-smoke.ts","push:android:watch": "node scripts/android-push-watch.ts","destroy": "alchemy destroy",diff --git a/infra/relay/scripts/deploy.test.ts b/infra/relay/scripts/deploy.test.tsdeleted file mode 100644index 4447c3493fb..00000000000--- a/infra/relay/scripts/deploy.test.ts+++ /dev/null@@ -1,227 +0,0 @@-import * as NodeServices from "@effect/platform-node/NodeServices";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as FileSystem from "effect/FileSystem";-import * as Path from "effect/Path";--import {- hasDeployChanges,- missingRelayPublicConfigFields,- publicConfigFromOutput,- reconcileRootEnvPublicConfig,- RelayDeployError,- RelayDeployPublicConfigUnavailableError,- serializeGithubOutput,- serializeRelayClientTracingEnvironment,-} from "./deploy.ts";--describe("RelayDeployError", () => {- it("reports the incomplete state source, stage, and missing fields", () => {- const missingFields = missingRelayPublicConfigFields({- url: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- });- const error = new RelayDeployError({- source: "alchemy_state",- stage: "production",- missingFields,- });-- expect(error).toMatchObject({- source: "alchemy_state",- stage: "production",- missingFields: [- "mobileTracingDataset",- "mobileTracingToken",- "clientTracingUrl",- "clientTracingDataset",- "clientTracingToken",- ],- });- expect(error.message).toBe(- "Relay deploy output from 'alchemy_state' for stage 'production' is missing required public config fields: mobileTracingDataset, mobileTracingToken, clientTracingUrl, clientTracingDataset, clientTracingToken",- );- });-- it("distinguishes deploy results that do not produce public config", () => {- const error = new RelayDeployPublicConfigUnavailableError({- result: "dry-run",- stage: "production",- outputPath: "/tmp/relay-client.env",- });-- expect(error.message).toBe(- "Relay deploy result 'dry-run' for stage 'production' did not produce public config required by GitHub environment output '/tmp/relay-client.env'.",- );- });-});--describe("hasDeployChanges", () => {- it("detects resource, binding, and deletion changes", () => {- expect(hasDeployChanges({ resources: {}, deletions: {} } as never)).toBe(false);- expect(- hasDeployChanges({- resources: {- api: { action: "create", bindings: [] },- },- deletions: {},- } as never),- ).toBe(true);- expect(- hasDeployChanges({- resources: {- api: { action: "noop", bindings: [{ action: "update" }] },- },- deletions: {},- } as never),- ).toBe(true);- expect(- hasDeployChanges({- resources: {},- deletions: {- api: { action: "delete", bindings: [] },- },- } as never),- ).toBe(true);- });-});--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",- clientTracingUrl: "https://api.axiom.co/v1/traces",- clientTracingDataset: "t3-code-relay-client-traces-dev",- clientTracingToken: "xaat-relay-client-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",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=t3-code-relay-client-traces-dev",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=xaat-relay-client-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",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://old.example.test/v1/traces",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=old-client-dataset",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=old-client-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",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=t3-code-relay-client-traces-dev",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=xaat-relay-client-ingest",- "",- ].join("\n"),- );- });-});--describe("serializeGithubOutput", () => {- it("serializes relay deploy metadata for GitHub Actions outputs", () => {- expect(- serializeGithubOutput({- changed: false,- result: "noop",- relay_url: "https://relay.example.test",- }),- ).toBe("changed=false\nresult=noop\nrelay_url=https://relay.example.test\n");- });-});--describe("serializeRelayClientTracingEnvironment", () => {- it("serializes tracing config for downstream GITHUB_ENV loading", () => {- expect(- serializeRelayClientTracingEnvironment({- relayUrl: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- mobileTracingDataset: "mobile",- mobileTracingToken: "mobile-token",- clientTracingUrl: "https://api.axiom.co/v1/traces",- clientTracingDataset: "relay",- clientTracingToken: "client-token",- }),- ).toBe(- [- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=relay",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=client-token",- "",- ].join("\n"),- );- });-});--describe("release workflow tracing config propagation", () => {- it.effect("uses an artifact instead of a masked cross-job token output", () =>- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const workflowPath = yield* path.fromFileUrl(- new URL("../../../.github/workflows/release.yml", import.meta.url),- );- const workflow = yield* fileSystem.readFileString(workflowPath);-- expect(workflow).not.toContain("client_tracing_token:");- expect(workflow).not.toContain("needs.relay_public_config.outputs.client_tracing_token");- expect(workflow).toContain('--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"');- expect(workflow).toContain("name: relay-client-tracing-config");- expect(workflow).toContain('cat "$config_path" >> "$GITHUB_ENV"');- }).pipe(Effect.provide(NodeServices.layer)),- );-});--describe("publicConfigFromOutput", () => {- it("reads the complete public tracing config from persisted Alchemy output", () => {- expect(- publicConfigFromOutput({- url: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- mobileTracingDataset: "mobile",- mobileTracingToken: "mobile-token",- clientTracingUrl: "https://api.axiom.co/v1/traces",- clientTracingDataset: "relay",- clientTracingToken: "client-token",- }),- ).toEqual({- relayUrl: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- mobileTracingDataset: "mobile",- mobileTracingToken: "mobile-token",- clientTracingUrl: "https://api.axiom.co/v1/traces",- clientTracingDataset: "relay",- clientTracingToken: "client-token",- });- });-- it("rejects incomplete stack output", () => {- expect(publicConfigFromOutput({ url: "https://relay.example.test" })).toBeNull();- });-});diff --git a/infra/relay/scripts/deploy.ts b/infra/relay/scripts/deploy.tsdeleted file mode 100644index df0a89afa80..00000000000--- a/infra/relay/scripts/deploy.ts+++ /dev/null@@ -1,504 +0,0 @@-#!/usr/bin/env node--import * as NodeRuntime from "@effect/platform-node/NodeRuntime";-import { AdoptPolicy } from "alchemy/AdoptPolicy";-import { AlchemyContext, AlchemyContextLive } from "alchemy/AlchemyContext";-import * as Apply from "alchemy/Apply";-import { ArtifactStore, createArtifactStore, provideFreshArtifactStore } from "alchemy/Artifacts";-import { AuthProviders } from "alchemy/Auth/AuthProvider";-import { CredentialsStoreLive } from "alchemy/Auth/Credentials";-import { ProfileStoreLive } from "alchemy/Auth/Profile";-import * as Cloudflare from "alchemy/Cloudflare";-import { layerNonInteractive } from "alchemy/Interaction";-import { LoggingCli } from "alchemy/Cli/LoggingCli";-import * as Plan from "alchemy/Plan";-import { Cli } from "alchemy/Report";-import * as Stage from "alchemy/Stage";-import * as State from "alchemy/State/State";-import { TelemetryLive } from "alchemy/Telemetry/Layer";-import { PlatformServices } from "alchemy/Util/PlatformServices";-import * as Config from "effect/Config";-import * as ConfigProvider from "effect/ConfigProvider";-import * as Console from "effect/Console";-import * as Effect from "effect/Effect";-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 * as Schema from "effect/Schema";-import { Command, Flag, Prompt } from "effect/unstable/cli";-import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";--import RelayStack from "../alchemy.run.ts";--const relayDeployOutputFields = [- "url",- "mobileTracingUrl",- "mobileTracingDataset",- "mobileTracingToken",- "clientTracingUrl",- "clientTracingDataset",- "clientTracingToken",-] as const;--export const RelayDeployOutputField = Schema.Literals(relayDeployOutputFields);-export type RelayDeployOutputField = typeof RelayDeployOutputField.Type;--export const RelayDeployResult = Schema.Literals([- "applied",- "noop",- "dry-run",- "cancelled",- "state",-]);-export type RelayDeployResult = typeof RelayDeployResult.Type;--export class RelayDeployError extends Schema.TaggedError<RelayDeployError>()("RelayDeployError", {- source: Schema.Literals(["alchemy_state", "alchemy_apply"]),- stage: Schema.String,- missingFields: Schema.Array(RelayDeployOutputField),-}) {- override get message(): string {- return `Relay deploy output from '${this.source}' for stage '${this.stage}' is missing required public config fields: ${this.missingFields.join(", ")}`;- }-}--export class RelayDeployPublicConfigUnavailableError extends Schema.TaggedError<RelayDeployPublicConfigUnavailableError>()(- "RelayDeployPublicConfigUnavailableError",- {- result: RelayDeployResult,- stage: Schema.String,- outputPath: Schema.String,- },-) {- override get message(): string {- return `Relay deploy result '${this.result}' for stage '${this.stage}' did not produce public config required by GitHub environment output '${this.outputPath}'.`;- }-}--export interface RelayDeployOptions {- readonly dryRun: boolean;- readonly force: boolean;- readonly envFile: Option.Option<string>;- readonly stage: Option.Option<string>;- readonly yes: boolean;- readonly adopt: boolean;- readonly githubOutput: boolean;- readonly githubEnvFile: Option.Option<string>;- readonly readState: boolean;-}--export interface RelayPublicConfig {- readonly relayUrl: string;- readonly mobileTracingUrl: string;- readonly mobileTracingDataset: string;- readonly mobileTracingToken: string;- readonly clientTracingUrl: string;- readonly clientTracingDataset: string;- readonly clientTracingToken: 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,- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.clientTracingToken,- }) 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 {- return reconcileRootEnvPublicConfig(contents, {- relayUrl,- mobileTracingUrl: "",- mobileTracingDataset: "",- mobileTracingToken: "",- clientTracingUrl: "",- clientTracingDataset: "",- clientTracingToken: "",- })- .split("\n")- .filter((line) => !line.startsWith("T3CODE_MOBILE_OTLP_TRACES_"))- .filter((line) => !line.startsWith("T3CODE_RELAY_CLIENT_OTLP_TRACES_"))- .join("\n");-}--export function hasDeployChanges(plan: Plan.Plan): boolean {- return (- Object.keys(plan.deletions).length > 0 ||- Object.values(plan.resources).some(- (node) =>- node.action !== "noop" || node.bindings.some((binding) => binding.action !== "noop"),- )- );-}--export interface RelayDeployOutcome {- readonly result: RelayDeployResult;- readonly changed: boolean;- readonly publicConfig: Option.Option<RelayPublicConfig>;-}--export function serializeGithubOutput(entries: Readonly<Record<string, string | boolean>>): string {- return Object.entries(entries)- .map(([key, value]) => `${key}=${value}\n`)- .join("");-}--export function serializeRelayClientTracingEnvironment(config: RelayPublicConfig): string {- return serializeGithubOutput({- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.clientTracingToken,- });-}--const relayRoot = Effect.service(Path.Path).pipe(- Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),-);-const repoRoot = Effect.service(Path.Path).pipe(- Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),-);--const loadDeployConfigProvider = Effect.fn("relay.deploy.loadConfigProvider")(function* (- envFileOverride: Option.Option<string>,-) {- const path = yield* Path.Path;- const root = yield* relayRoot;-- if (Option.isSome(envFileOverride)) {- return yield* ConfigProvider.fromDotEnv({ path: path.resolve(root, envFileOverride.value) });- }-- return yield* ConfigProvider.fromDotEnv({ path: path.join(root, ".env") }).pipe(- Effect.orElseSucceed(() => ConfigProvider.fromEnv()),- );-});--const relayDeployStage = Config.NonEmptyString("stage").pipe(- Config.option,- Config.map(- Option.getOrElse(() => `dev_${process.env.USER ?? process.env.USERNAME ?? "unknown"}`),- ),-);--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, reconcileRootEnvPublicConfig(contents, config));- yield* Console.log(`Updated ${rootEnvPath} with relay public client configuration`);-});--const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function* (- outcome: RelayDeployOutcome,-) {- const fs = yield* FileSystem.FileSystem;- const githubOutputPath = yield* Config.NonEmptyString("GITHUB_OUTPUT");- yield* fs.writeFileString(- githubOutputPath,- serializeGithubOutput({- changed: outcome.changed,- result: outcome.result,- ...(Option.isSome(outcome.publicConfig)- ? {- relay_url: outcome.publicConfig.value.relayUrl,- }- : {}),- }),- { flag: "a" },- );-});--const writeGithubEnvFile = Effect.fn("relay.deploy.writeGithubEnvFile")(function* (- outcome: RelayDeployOutcome,- outputPath: string,- stage: string,-) {- if (Option.isNone(outcome.publicConfig)) {- return yield* new RelayDeployPublicConfigUnavailableError({- result: outcome.result,- stage,- outputPath,- });- }- const fs = yield* FileSystem.FileSystem;- yield* Console.log(`::add-mask::${outcome.publicConfig.value.clientTracingToken}`);- yield* fs.writeFileString(- outputPath,- serializeRelayClientTracingEnvironment(outcome.publicConfig.value),- );-});--const deployBaseServices = Layer.mergeAll(- Layer.succeed(AuthProviders, {}),- Layer.succeed(ArtifactStore, createArtifactStore()),- Layer.provideMerge(AlchemyContextLive, PlatformServices),- Layer.provide(ProfileStoreLive, PlatformServices),- Layer.provide(CredentialsStoreLive, PlatformServices),- FetchHttpClient.layer,- TelemetryLive,- // LoggingCli captures the prompt environment when it is built.- Layer.provide(LoggingCli, PlatformServices),- // Alchemy's auth providers prompt through this service. None are configured- // here and the apply confirmation is this script's own prompt, so a prompt- // reaching it is a typed failure rather than a hang in CI.- layerNonInteractive(),-);-const deployServices = deployBaseServices;--function relayPublicConfigValues(- output: unknown,-): Readonly<Record<RelayDeployOutputField, string | undefined>> {- if (typeof output !== "object" || output === null) {- return {- url: undefined,- mobileTracingUrl: undefined,- mobileTracingDataset: undefined,- mobileTracingToken: undefined,- clientTracingUrl: undefined,- clientTracingDataset: undefined,- clientTracingToken: undefined,- };- }- const value = output as Record<string, unknown>;- const text = (name: string) => {- const candidate = value[name];- return typeof candidate === "string" && candidate.length > 0 ? candidate : undefined;- };- const secret = (name: string): string | undefined => {- const candidate = value[name];- if (!Redacted.isRedacted(candidate)) {- return text(name);- }- const redacted = Redacted.value(candidate);- return typeof redacted === "string" && redacted.length > 0 ? redacted : undefined;- };- return {- url: text("url"),- mobileTracingUrl: text("mobileTracingUrl"),- mobileTracingDataset: text("mobileTracingDataset"),- mobileTracingToken: secret("mobileTracingToken"),- clientTracingUrl: text("clientTracingUrl"),- clientTracingDataset: text("clientTracingDataset"),- clientTracingToken: secret("clientTracingToken"),- };-}--export function missingRelayPublicConfigFields(- output: unknown,-): ReadonlyArray<RelayDeployOutputField> {- const values = relayPublicConfigValues(output);- return relayDeployOutputFields.filter((field) => values[field] === undefined);-}--function hasCompleteRelayPublicConfigValues(- values: Readonly<Record<RelayDeployOutputField, string | undefined>>,-): values is Readonly<Record<RelayDeployOutputField, string>> {- return relayDeployOutputFields.every((field) => values[field] !== undefined);-}--export function publicConfigFromOutput(output: unknown): RelayPublicConfig | null {- const values = relayPublicConfigValues(output);- if (!hasCompleteRelayPublicConfigValues(values)) {- return null;- }- return {- relayUrl: values.url,- mobileTracingUrl: values.mobileTracingUrl,- mobileTracingDataset: values.mobileTracingDataset,- mobileTracingToken: values.mobileTracingToken,- clientTracingUrl: values.clientTracingUrl,- clientTracingDataset: values.clientTracingDataset,- clientTracingToken: values.clientTracingToken,- };-}--const readRelayPublicConfig = Effect.fn("relay.deploy.readState")(function* (stage: string) {- const state = yield* State.State;- const service = yield* state;- const output = yield* service.getOutput({ stack: "T3CodeRelay", stage });- const publicConfig = publicConfigFromOutput(output);- if (publicConfig === null) {- return yield* new RelayDeployError({- source: "alchemy_state",- stage,- missingFields: missingRelayPublicConfigFields(output),- });- }- return {- result: "state",- changed: false,- publicConfig: Option.some(publicConfig),- } satisfies RelayDeployOutcome;-});--const runRelayDeploy = Effect.fn("relay.deploy.run")(- function* (- options: RelayDeployOptions,- _configProvider: ConfigProvider.ConfigProvider,- stage: string,- ) {- const stack = yield* RelayStack;- const cli = yield* Cli;- const plan = yield* Plan.make(stack, { force: options.force }).pipe(- Effect.provide(stack.services),- );- const changed = hasDeployChanges(plan);- if (options.dryRun) {- yield* cli.displayPlan(plan);- return {- result: "dry-run",- changed,- publicConfig: Option.none<RelayPublicConfig>(),- } satisfies RelayDeployOutcome;- }- if (!options.yes && changed) {- yield* cli.displayPlan(plan);- const approved = yield* Prompt.run(- Prompt.Confirm({- message: "Apply this relay deployment?",- }),- );- if (!approved) {- yield* Console.log("Deployment cancelled.");- return {- result: "cancelled",- changed,- publicConfig: Option.none<RelayPublicConfig>(),- } satisfies RelayDeployOutcome;- }- }- const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));- const publicConfig = publicConfigFromOutput(output);- if (publicConfig === null) {- return yield* new RelayDeployError({- source: "alchemy_apply",- stage,- missingFields: missingRelayPublicConfigFields(output),- });- }- return {- result: changed ? "applied" : "noop",- changed,- publicConfig: Option.some(publicConfig),- } satisfies RelayDeployOutcome;- },- (effect, options, configProvider, stage) =>- effect.pipe(- Effect.provide(- Layer.mergeAll(- Layer.effect(- AlchemyContext,- AlchemyContext.pipe(Effect.map((context) => ({ ...context, adopt: options.adopt }))),- ),- Layer.succeed(AdoptPolicy, options.adopt),- Layer.succeed(AuthProviders, {}),- ConfigProvider.layer(configProvider),- Layer.succeed(Stage.Stage, stage),- ),- ),- provideFreshArtifactStore,- ),-);--export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployOptions) {- const configProvider = yield* loadDeployConfigProvider(options.envFile);- const configuredStage = yield* relayDeployStage.pipe(- Effect.provide(ConfigProvider.layer(configProvider)),- );- const stage = Option.getOrElse(options.stage, () => configuredStage);- const outcome = options.readState- ? yield* readRelayPublicConfig(stage).pipe(Effect.provide(Cloudflare.state()))- : yield* runRelayDeploy(options, configProvider, stage);- if (Option.isSome(outcome.publicConfig)) {- yield* reconcileRootEnv(outcome.publicConfig.value);- }- if (options.githubOutput) {- yield* writeGithubOutput(outcome);- }- if (Option.isSome(options.githubEnvFile)) {- yield* writeGithubEnvFile(outcome, options.githubEnvFile.value, stage);- }-});--export const relayDeployCommand = Command.make(- "relay-deploy",- {- dryRun: Flag.Boolean("dry-run").pipe(- Flag.withDescription("Dry run the deployment without applying changes."),- Flag.withDefault(false),- ),- force: Flag.Boolean("force").pipe(- Flag.withDescription("Force updates for resources that would otherwise no-op."),- Flag.withDefault(false),- ),- envFile: Flag.String("env-file").pipe(- Flag.withDescription(- "Environment file to load. Defaults to infra/relay/.env with process env fallback.",- ),- Flag.optional,- ),- stage: Flag.String("stage").pipe(- Flag.withDescription("Stage to deploy. Defaults to dev_${USER}."),- Flag.optional,- ),- yes: Flag.Boolean("yes").pipe(- Flag.withDescription("Skip the deployment confirmation prompt."),- Flag.withDefault(false),- ),- adopt: Flag.Boolean("adopt").pipe(- Flag.withDescription("Adopt pre-existing cloud resources that conflict with this stack."),- Flag.withDefault(false),- ),- githubOutput: Flag.Boolean("github-output").pipe(- Flag.withDescription("Append relay deployment metadata to GITHUB_OUTPUT."),- Flag.withDefault(false),- ),- githubEnvFile: Flag.String("github-env-file").pipe(- Flag.withDescription(- "Write relay client tracing variables to a file suitable for GITHUB_ENV.",- ),- Flag.optional,- ),- readState: Flag.Boolean("read-state").pipe(- Flag.withDescription("Read the deployed stack output without planning or applying changes."),- Flag.withDefault(false),- ),- },- deploy,-).pipe(Command.withDescription("Deploy the T3 Code relay through Alchemy."));--if (import.meta.main) {- Command.run(relayDeployCommand, { version: "0.0.0" }).pipe(- Effect.provide(deployServices),- Effect.scoped,- NodeRuntime.runMain,- );-}diff --git a/infra/relay/src/clientConfig.test.ts b/infra/relay/src/clientConfig.test.tsnew file mode 100644index 00000000000..6fd28dcd948--- /dev/null+++ b/infra/relay/src/clientConfig.test.ts@@ -0,0 +1,177 @@+// @effect-diagnostics anyUnknownInErrorContext:off - ScratchStack.deploy is typed with `any` in its error channel by Alchemy.+import { inMemoryState } from "alchemy/State";+import * as Test from "alchemy/Test/Vitest";+import * as ConfigProvider from "effect/ConfigProvider";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Path from "effect/Path";+import * as Redacted from "effect/Redacted";+import { describe, expect, it } from "vite-plus/test";+import * as NodeServices from "@effect/platform-node/NodeServices";++import { PublishClientConfig, reconcileEnvFile, tokenDigest } from "./clientConfig.ts";++describe("reconcileEnvFile", () => {+ it("adds every entry to an empty file", () => {+ expect(reconcileEnvFile("", { A: "1", B: "2" })).toBe("A=1\nB=2\n");+ });++ it("replaces stale values and keeps unrelated lines", () => {+ const existing = "KEEP=yes\nA=old\n# comment\n";+ expect(reconcileEnvFile(existing, { A: "new", B: "2" })).toBe(+ "KEEP=yes\nA=new\n# comment\nB=2\n",+ );+ });++ it("appends a newline before adding to a file without one", () => {+ expect(reconcileEnvFile("A=1", { B: "2" })).toBe("A=1\nB=2\n");+ });++ it("collapses duplicate assignments to one, since parseEnv lets the last win", () => {+ expect(reconcileEnvFile("A=old\nKEEP=1\nA=older\n", { A: "new" })).toBe("A=new\nKEEP=1\n");+ });++ it("recognises every assignment form parseEnv accepts", () => {+ expect(reconcileEnvFile("A=old\n export A = stale\nexport A=older\n", { A: "new" })).toBe(+ "A=new\n",+ );+ });++ it("replaces a quoted multi-line value whole", () => {+ expect(reconcileEnvFile('A="one\ntwo"\nKEEP=1\n', { A: "new" })).toBe("A=new\nKEEP=1\n");+ expect(reconcileEnvFile("A='x'\nKEEP=1\n", { A: "new" })).toBe("A=new\nKEEP=1\n");+ });++ it("keeps later lines when a quoted value never closes", () => {+ expect(reconcileEnvFile('A="one\nKEEP=1\n', { A: "new" })).toBe("A=new\nKEEP=1\n");+ });++ it("leaves a commented-out assignment alone", () => {+ expect(reconcileEnvFile("#A=old\n", { A: "new" })).toBe("#A=old\nA=new\n");+ });+});++const { test } = Test.make({+ providers: Layer.empty,+ state: inMemoryState(),+});++const clientConfig = (token: string) => ({+ url: "https://relay.example.com",+ mobileTracingUrl: "https://axiom.example.com/v1/traces",+ mobileTracingDataset: "relay-traces",+ mobileTracingToken: Redacted.make(`mobile-${token}`),+ clientTracingUrl: "https://axiom.example.com/v1/traces",+ clientTracingDataset: "relay-traces",+ clientTracingToken: Redacted.make(`client-${token}`),+ tokenDigest: tokenDigest([Redacted.make(`mobile-${token}`), Redacted.make(`client-${token}`)]),+});++describe("PublishClientConfig", () => {+ test.provider("writes the env file on deploy and skips an unchanged redeploy", (stack) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-relay-client-config-" });+ const target = path.join(dir, "client.env");+ yield* fs.writeFileString(target, "KEEP=yes\n");+ const configured = Effect.provide(+ ConfigProvider.layer(+ ConfigProvider.fromUnknown({ T3CODE_RELAY_CLIENT_CONFIG_ENV: target }),+ ),+ );++ yield* stack+ .deploy(+ Effect.gen(function* () {+ return yield* PublishClientConfig(clientConfig("v1"));+ }),+ )+ .pipe(configured);+ const first = yield* fs.readFileString(target);+ expect(first).toContain("KEEP=yes\n");+ expect(first).toContain("T3CODE_RELAY_URL=https://relay.example.com\n");+ expect(first).toContain("T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=client-v1\n");+ expect(first).toContain("T3CODE_MOBILE_OTLP_TRACES_TOKEN=mobile-v1\n");++ // Same input: the action is skipped, so a change made by hand survives.+ yield* fs.writeFileString(target, `${first}MANUAL=1\n`);+ yield* stack+ .deploy(+ Effect.gen(function* () {+ return yield* PublishClientConfig(clientConfig("v1"));+ }),+ )+ .pipe(configured);+ expect(yield* fs.readFileString(target)).toContain("MANUAL=1\n");++ // A rotated token changes the input, so it runs again and replaces the line.+ yield* stack+ .deploy(+ Effect.gen(function* () {+ return yield* PublishClientConfig(clientConfig("v2"));+ }),+ )+ .pipe(configured);+ const third = yield* fs.readFileString(target);+ expect(third).toContain("T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=client-v2\n");+ expect(third).not.toContain("client-v1");+ expect(third).toContain("KEEP=yes\n");+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ test.provider("fails when the worker has no url rather than publishing an empty relay", (stack) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-relay-client-config-" });+ const target = path.join(dir, "client.env");+ const exit = yield* stack+ .deploy(+ Effect.gen(function* () {+ return yield* PublishClientConfig({ ...clientConfig("v1"), url: undefined });+ }),+ )+ .pipe(+ Effect.provide(+ ConfigProvider.layer(+ ConfigProvider.fromUnknown({ T3CODE_RELAY_CLIENT_CONFIG_ENV: target }),+ ),+ ),+ Effect.exit,+ );+ expect(exit._tag).toBe("Failure");+ expect(String(exit)).toContain("RelayUrlUnavailableError");+ expect(yield* fs.exists(target)).toBe(false);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ test.provider("refuses a value with a line break rather than corrupting the file", (stack) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-relay-client-config-" });+ const target = path.join(dir, "client.env");+ const exit = yield* stack+ .deploy(+ Effect.gen(function* () {+ return yield* PublishClientConfig({+ ...clientConfig("v1"),+ clientTracingDataset: "relay-traces\nINJECTED=1",+ });+ }),+ )+ .pipe(+ Effect.provide(+ ConfigProvider.layer(+ ConfigProvider.fromUnknown({ T3CODE_RELAY_CLIENT_CONFIG_ENV: target }),+ ),+ ),+ Effect.exit,+ );+ expect(exit._tag).toBe("Failure");+ expect(yield* fs.exists(target)).toBe(false);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );+});diff --git a/infra/relay/src/clientConfig.ts b/infra/relay/src/clientConfig.tsnew file mode 100644index 00000000000..f6afe175587--- /dev/null+++ b/infra/relay/src/clientConfig.ts@@ -0,0 +1,144 @@+// @effect-diagnostics nodeBuiltinImport:off - one sha256 over two strings; Effect.Crypto is async and the digest feeds a synchronous Output.map.+import * as NodeCrypto from "node:crypto";++import * as Alchemy from "alchemy";+import * as Config from "effect/Config";+import * as Console from "effect/Console";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as Redacted from "effect/Redacted";+import * as Schema from "effect/Schema";++/** The relay outputs a client (web, desktop, mobile) needs at build time. */+export interface RelayClientConfig {+ /** Alchemy types this as optional for workers reachable at no URL; ours always has one. */+ readonly url: string | undefined;+ readonly mobileTracingUrl: string;+ readonly mobileTracingDataset: string;+ readonly mobileTracingToken: Redacted.Redacted<string>;+ readonly clientTracingUrl: string;+ readonly clientTracingDataset: string;+ readonly clientTracingToken: Redacted.Redacted<string>;+ /**+ * Alchemy decides whether an Action runs by hashing `JSON.stringify` of its+ * input, and a Redacted stringifies as `<redacted>`, so a rotated token+ * alone would never re-run it. A digest of both tokens makes the input+ * change with them without persisting the secrets in the hash.+ */+ readonly tokenDigest: string;+}++export class RelayUrlUnavailableError extends Schema.TaggedError<RelayUrlUnavailableError>()(+ "RelayUrlUnavailableError",+ {},+) {+ override get message(): string {+ return "The relay worker has no URL yet; deploy again once the worker exists.";+ }+}++export const relayClientConfigEnv = (config: RelayClientConfig & { readonly url: string }) =>+ ({+ T3CODE_RELAY_URL: config.url,+ T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileTracingUrl,+ T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileTracingDataset,+ T3CODE_MOBILE_OTLP_TRACES_TOKEN: Redacted.value(config.mobileTracingToken),+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: Redacted.value(config.clientTracingToken),+ }) as const;++export class EnvValueNotSingleLineError extends Schema.TaggedError<EnvValueNotSingleLineError>()(+ "EnvValueNotSingleLineError",+ { name: Schema.String },+) {+ override get message(): string {+ return `${this.name} contains a line break and cannot be written as one .env assignment.`;+ }+}++/**+ * Replaces or appends each `NAME=value` assignment, leaving unrelated lines+ * alone. Every existing line for a name is dropped, not just the first: the+ * file is read with `parseEnv`, where the last duplicate wins, so a stale+ * second copy would override the value just written.+ */+export function reconcileEnvFile(+ contents: string,+ entries: Readonly<Record<string, string>>,+): string {+ const lines = contents === "" ? [] : contents.replace(/\n$/u, "").split("\n");+ // The forms `parseEnv` treats as an assignment: leading whitespace, an+ // optional `export`, and whitespace around `=`.+ const assignment = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/u;+ const pending = new Map(Object.entries(entries));+ const out: string[] = [];+ for (let index = 0; index < lines.length; index += 1) {+ const line = lines[index]!;+ const match = assignment.exec(line);+ const name = match?.[1];+ if (match === null || name === undefined || !(name in entries)) {+ out.push(line);+ continue;+ }+ // A quoted value can span lines; skip to its closing quote so the+ // continuation lines go with the assignment they belong to. With no+ // closing quote in the file, parseEnv treats the opening line as the+ // whole value, so nothing after it is consumed.+ const rawValue = match[2] ?? "";+ const quote = /^(['"`])/u.exec(rawValue)?.[1];+ if (quote !== undefined && !closesQuote(rawValue, quote)) {+ const closing = lines.findIndex((candidate, at) => at > index && candidate.includes(quote));+ if (closing !== -1) index = closing;+ }+ // The first occurrence keeps its position; later duplicates are dropped.+ const value = pending.get(name);+ if (value !== undefined) {+ out.push(`${name}=${value}`);+ pending.delete(name);+ }+ }+ for (const [name, value] of pending) out.push(`${name}=${value}`);+ return out.length === 0 ? "" : `${out.join("\n")}\n`;+}++/** Whether a value that opens with `quote` also closes on the same line. */+const closesQuote = (value: string, quote: string): boolean =>+ value.length > 1 && value.slice(1).includes(quote);++/**+ * Writes the relay's client configuration into the repo-root `.env` so the+ * web, desktop, and mobile dev servers build against the stage just deployed.+ * An Action rather than post-deploy scripting: it takes the stack outputs as+ * input, so it runs only when one of them changed and is skipped on a no-op+ * deploy. Set `T3CODE_RELAY_CLIENT_CONFIG_ENV` to write elsewhere (CI does).+ */+export const tokenDigest = (tokens: ReadonlyArray<Redacted.Redacted<string>>): string =>+ NodeCrypto.createHash("sha256").update(tokens.map(Redacted.value).join("\n")).digest("hex");++export const PublishClientConfig = Alchemy.Action(+ "PublishClientConfig",+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const override = yield* Config.String("T3CODE_RELAY_CLIENT_CONFIG_ENV").pipe(Config.option);+ const repoRootEnv = path.fromFileUrl(new URL("../../../.env", import.meta.url));+ const target = Option.isSome(override) ? override.value : yield* repoRootEnv;+ return Effect.fn(function* (input: RelayClientConfig) {+ const url = input.url;+ if (url === undefined) return yield* new RelayUrlUnavailableError();+ const entries = relayClientConfigEnv({ ...input, url });+ // Provider responses are copied in verbatim; a line break in one would+ // become an extra assignment.+ for (const [name, value] of Object.entries(entries)) {+ if (/[\r\n]/u.test(value)) return yield* new EnvValueNotSingleLineError({ name });+ }+ const existing = (yield* fs.exists(target)) ? yield* fs.readFileString(target) : "";+ yield* fs.writeFileString(target, reconcileEnvFile(existing, entries));+ yield* Console.log(`Wrote relay client configuration to ${target}`);+ return { path: target };+ });+ }),+);