The best way to control Claude Code, Codex and more from any computer or phone
feat(relay): deploy on-demand preview stages for labeled PRs
Labeled same-repo PRs deploy stage pr-<n> behind the relay-preview environment reviewer gate. Unlabel or close tears the stage down, and a nightly job retries failed teardowns. Runtime-created managed endpoint tunnels and CNAMEs are swept by a PreviewTunnelSweep resource. Known gaps, tracked as follow-ups: an interrupted preview deploy can leave runtime tunnels behind; repo-level relay secrets still bypass the environment gate until moved. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Julius Marminge committed
Oct 23, 2026 at 19:28 UTC
ff1f6fd8849cdd2e0a07096eac4fd4440d1ad989
9 files changed
+726
-3
.github/workflows/relay-preview-cleanup.yml
new
+203
@@ -0,0 +1,203 @@
1
+name: Clean up relay preview
2
+
3
+# Tears down stage `pr-<n>` when `relay:preview` is removed or the PR closes,
4
+# and retries teardown for closed labeled PRs on a schedule. A label stays on a
5
+# PR only while its teardown is outstanding, so the scheduled retry lists
6
+# exactly the failures.
7
+#
8
+# This runs under pull_request_target, so the workflow and the Alchemy program
9
+# come from the default branch. No PR code runs here, which is why it needs no
10
+# reviewer approval and why a PR cannot edit its own teardown to reach secrets.
11
+on:
12
+ pull_request_target:
13
+ types: [unlabeled, closed]
14
+ schedule:
15
+ - cron: "17 7 * * *"
16
+ workflow_dispatch:
17
+
18
+permissions:
19
+ contents: read
20
+ issues: read
21
+ pull-requests: read
22
+
23
+jobs:
24
+ cleanup_pr:
25
+ name: Tear down relay preview
26
+ if: >-
27
+ github.ref == 'refs/heads/main' &&
28
+ github.event_name == 'pull_request_target' &&
29
+ (
30
+ (github.event.action == 'unlabeled' && github.event.label.name == 'relay:preview') ||
31
+ (github.event.action == 'closed' && contains(github.event.pull_request.labels.*.name, 'relay:preview'))
32
+ )
33
+ # Job-level so that events which skip this job, such as a closed PR without
34
+ # the label, never take the group's pending slot. GitHub replaces a pending
35
+ # run in a group with a newer one, which would drop a queued teardown.
36
+ concurrency:
37
+ group: relay-preview-${{ github.event.pull_request.number }}
38
+ cancel-in-progress: false
39
+ permissions:
40
+ contents: read
41
+ issues: write
42
+ pull-requests: write
43
+ runs-on: blacksmith-8vcpu-ubuntu-2404
44
+ timeout-minutes: 30
45
+ environment:
46
+ name: relay-preview-cleanup
47
+ env:
48
+ GH_TOKEN: ${{ github.token }}
49
+ STAGE: pr-${{ github.event.pull_request.number }}
50
+ CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
51
+ PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
52
+ AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
53
+ RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
54
+ RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
55
+ CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
56
+ CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
57
+ APNS_ENABLED: "false"
58
+ ALCHEMY_TELEMETRY_DISABLED: "1"
59
+ steps:
60
+ - name: Checkout default branch
61
+ uses: actions/checkout@v6
62
+ with:
63
+ ref: ${{ github.event.repository.default_branch }}
64
+ sparse-checkout: |
65
+ /*
66
+ !/.repos/
67
+ sparse-checkout-cone-mode: false
68
+
69
+ - name: Setup Vite+
70
+ uses: voidzero-dev/setup-vp@v1
71
+ with:
72
+ node-version-file: package.json
73
+ cache: true
74
+ run-install: |
75
+ args:
76
+ - --filter=t3code-relay...
77
+
78
+ # Destroy also runs the preview tunnel sweep, which is part of the stack.
79
+ - name: Destroy preview stage
80
+ run: vp run --filter t3code-relay destroy --stage "$STAGE" --yes --no-input
81
+ env:
82
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
83
+ PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
84
+ PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
85
+ AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
86
+ CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
87
+
88
+ # Only reached after a successful destroy. A failed one keeps the label,
89
+ # so the scheduled retry picks the PR up again.
90
+ - name: Clear the teardown marker
91
+ if: github.event.action == 'closed'
92
+ run: gh pr edit "${{ github.event.pull_request.number }}" --repo "$GITHUB_REPOSITORY" --remove-label relay:preview
93
+
94
+ # An unlabeled event has already removed the label, so a failed teardown
95
+ # must put it back or no retry will ever see the stage. Labels added with
96
+ # GITHUB_TOKEN do not start new runs, so this does not redeploy.
97
+ - name: Restore the teardown marker after a failed destroy
98
+ if: failure() && github.event.action == 'unlabeled'
99
+ run: gh pr edit "${{ github.event.pull_request.number }}" --repo "$GITHUB_REPOSITORY" --add-label relay:preview
100
+
101
+ list_closed_previews:
102
+ name: List closed relay previews
103
+ if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request_target'
104
+ runs-on: blacksmith-8vcpu-ubuntu-2404
105
+ timeout-minutes: 10
106
+ outputs:
107
+ numbers: ${{ steps.list.outputs.numbers }}
108
+ steps:
109
+ # The issues endpoint is paginated by gh, so there is no listing cap. Pull
110
+ # requests appear there with a `pull_request` key.
111
+ - name: List closed PRs labeled relay:preview
112
+ id: list
113
+ env:
114
+ GH_TOKEN: ${{ github.token }}
115
+ run: |
116
+ numbers=$(gh api --paginate --method GET "repos/$GITHUB_REPOSITORY/issues" \
117
+ -f labels=relay:preview -f state=closed -f per_page=100 \
118
+ --jq '.[] | select(.pull_request) | .number') \
119
+ || { echo "Could not list closed relay:preview PRs" >&2; exit 1; }
120
+ json=$(printf '%s\n' "$numbers" | jq -Rsc 'split("\n") | map(select(length > 0) | tonumber)')
121
+ echo "Closed relay:preview PRs: $json"
122
+ echo "numbers=$json" >> "$GITHUB_OUTPUT"
123
+
124
+ sweep_pr:
125
+ name: Retry teardown for PR ${{ matrix.number }}
126
+ needs: list_closed_previews
127
+ if: github.ref == 'refs/heads/main' && needs.list_closed_previews.outputs.numbers != '[]'
128
+ runs-on: blacksmith-8vcpu-ubuntu-2404
129
+ timeout-minutes: 30
130
+ strategy:
131
+ fail-fast: false
132
+ max-parallel: 4
133
+ matrix:
134
+ number: ${{ fromJSON(needs.list_closed_previews.outputs.numbers) }}
135
+ # Same group as the deploy and teardown for this PR, so a reopened PR's
136
+ # deploy cannot run concurrently with a teardown of its previous stage.
137
+ concurrency:
138
+ group: relay-preview-${{ matrix.number }}
139
+ cancel-in-progress: false
140
+ permissions:
141
+ contents: read
142
+ issues: write
143
+ pull-requests: write
144
+ environment:
145
+ name: relay-preview-cleanup
146
+ env:
147
+ GH_TOKEN: ${{ github.token }}
148
+ STAGE: pr-${{ matrix.number }}
149
+ CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
150
+ PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
151
+ AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
152
+ RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
153
+ RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
154
+ CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
155
+ CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
156
+ APNS_ENABLED: "false"
157
+ ALCHEMY_TELEMETRY_DISABLED: "1"
158
+ steps:
159
+ # The lock above is taken before this runs, so the state read here is
160
+ # current. An open PR, including one reopened since the listing, is left
161
+ # alone. GitHub reports merged PRs as MERGED, so anything not OPEN counts.
162
+ - name: Confirm the PR is not open
163
+ id: eligible
164
+ run: |
165
+ state=$(gh pr view "${{ matrix.number }}" --repo "$GITHUB_REPOSITORY" \
166
+ --json state --jq 'if .state == "OPEN" then "no" else "yes" end') \
167
+ || { echo "Could not read PR ${{ matrix.number }}" >&2; exit 1; }
168
+ echo "eligible=$state" >> "$GITHUB_OUTPUT"
169
+ [ "$state" = yes ] || echo "PR ${{ matrix.number }} is open again; leaving $STAGE alone."
170
+
171
+ - name: Checkout default branch
172
+ if: steps.eligible.outputs.eligible == 'yes'
173
+ uses: actions/checkout@v6
174
+ with:
175
+ ref: ${{ github.event.repository.default_branch }}
176
+ sparse-checkout: |
177
+ /*
178
+ !/.repos/
179
+ sparse-checkout-cone-mode: false
180
+
181
+ - name: Setup Vite+
182
+ if: steps.eligible.outputs.eligible == 'yes'
183
+ uses: voidzero-dev/setup-vp@v1
184
+ with:
185
+ node-version-file: package.json
186
+ cache: true
187
+ run-install: |
188
+ args:
189
+ - --filter=t3code-relay...
190
+
191
+ - name: Destroy preview stage
192
+ if: steps.eligible.outputs.eligible == 'yes'
193
+ run: vp run --filter t3code-relay destroy --stage "$STAGE" --yes --no-input
194
+ env:
195
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
196
+ PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
197
+ PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
198
+ AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
199
+ CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
200
+
201
+ - name: Clear the teardown marker
202
+ if: steps.eligible.outputs.eligible == 'yes'
203
+ run: gh pr edit "${{ matrix.number }}" --repo "$GITHUB_REPOSITORY" --remove-label relay:preview
.github/workflows/relay-preview.yml
new
+81
@@ -0,0 +1,81 @@
1
+name: Deploy relay preview
2
+
3
+# Labeling a same-repository PR `relay:preview` deploys Alchemy stage `pr-<n>`.
4
+# This job runs the PR's own code with account credentials, so it waits for an
5
+# approval in the `relay-preview` environment on every run. Teardown is in
6
+# relay-preview-cleanup.yml and never runs PR code.
7
+on:
8
+ pull_request:
9
+ types: [labeled, synchronize, reopened]
10
+
11
+permissions:
12
+ contents: read
13
+ pull-requests: read
14
+
15
+concurrency:
16
+ group: relay-preview-${{ github.event.pull_request.number }}
17
+ cancel-in-progress: false
18
+
19
+jobs:
20
+ deploy_preview:
21
+ name: Deploy relay preview
22
+ if: >-
23
+ github.event.pull_request.head.repo.full_name == github.repository &&
24
+ contains(github.event.pull_request.labels.*.name, 'relay:preview')
25
+ runs-on: blacksmith-8vcpu-ubuntu-2404
26
+ timeout-minutes: 20
27
+ environment:
28
+ name: relay-preview
29
+ env:
30
+ STAGE: pr-${{ github.event.pull_request.number }}
31
+ CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
32
+ PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
33
+ AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
34
+ RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
35
+ RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
36
+ CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
37
+ CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
38
+ # Previews take no alert notifier, no tunnel cleanup, and no custom
39
+ # domain, so they stay silent and reap nothing outside their own stage.
40
+ APNS_ENABLED: "false"
41
+ ALCHEMY_TELEMETRY_DISABLED: "1"
42
+ steps:
43
+ - name: Confirm the PR is still open and labeled
44
+ env:
45
+ GH_TOKEN: ${{ github.token }}
46
+ PR_NUMBER: ${{ github.event.pull_request.number }}
47
+ run: |
48
+ state=$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --json state,labels \
49
+ --jq 'if .state == "OPEN" and any(.labels[]; .name == "relay:preview") then "ok" else "stale" end')
50
+ if [ "$state" != "ok" ]; then
51
+ echo "PR #$PR_NUMBER is no longer open with relay:preview; not deploying." >&2
52
+ exit 1
53
+ fi
54
+
55
+ - name: Checkout
56
+ uses: actions/checkout@v6
57
+ with:
58
+ ref: ${{ github.event.pull_request.head.sha }}
59
+ sparse-checkout: |
60
+ /*
61
+ !/.repos/
62
+ sparse-checkout-cone-mode: false
63
+
64
+ - name: Setup Vite+
65
+ uses: voidzero-dev/setup-vp@v1
66
+ with:
67
+ node-version-file: package.json
68
+ cache: true
69
+ run-install: |
70
+ args:
71
+ - --filter=t3code-relay...
72
+
73
+ - name: Deploy preview stage
74
+ run: vp run --filter t3code-relay deploy --stage "$STAGE" --yes --no-input
75
+ env:
76
+ T3CODE_RELAY_CLIENT_CONFIG_ENV: ${{ runner.temp }}/relay-client-config.env
77
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
78
+ PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
79
+ PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
80
+ AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
81
+ CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
docs/operations/release.md
+7
-1
@@ -160,12 +160,18 @@ database. Local personal stages provision isolated branches from it and are neve
160
Production adopts the configured relay API and tunnel DNS zones as retained Cloudflare resources.
161
Personal stages reference the production-owned zones.
162
163
-Developers deploy personal stages locally rather than through pull-request automation:
163
+Developers deploy personal stages locally:
164
165
```sh
166
vp run --filter t3code-relay deploy -- --stage "$USER" --env-file .env.local
167
```
168
169
+A same-repository PR labeled `relay:preview` deploys stage `pr-<number>` through
170
+`.github/workflows/relay-preview.yml`, after approval in the `relay-preview` environment. Removing the
171
+label or closing the PR runs `.github/workflows/relay-preview-cleanup.yml`, which destroys the stage
172
+and sweeps its managed tunnels and DNS records. A nightly run destroys stages of closed labeled PRs
173
+whose teardown failed. Fork PRs get no preview.
174
+
175
### Managed tunnel cleanup rollout
176
177
Keep `RELAY_TUNNEL_CLEANUP_MODE=off` for the first production deploy. That deploy applies the
infra/relay/README.md
+3
-1
@@ -120,7 +120,9 @@ one of those outputs changed, and `T3CODE_RELAY_CLIENT_CONFIG_ENV` redirects it
120
The relay is versioned separately from client releases. `.github/workflows/deploy-relay.yml` deploys
121
the shared Alchemy `prod` stage on every push to `main`. Stable and nightly release builds both
122
resolve their static public config from the same
123
-`production` GitHub environment. Pull requests do not deploy relay stages. Developers can
123
+`production` GitHub environment. Labeling a same-repository PR `relay:preview` deploys a `pr-<number>`
124
+stage, and the cleanup workflow tears it down; see
125
+[`relay-preview.yml`](../../.github/workflows/relay-preview.yml). Developers can
126
deploy personal non-production stages locally with any stage name other than `prod`.
127
128
The repository must define these Actions variables shared by relay deployments:
infra/relay/alchemy.run.ts
+13
-1
@@ -11,7 +11,9 @@ import * as Planetscale from "alchemy/Planetscale";
11
import { PublishClientConfig, tokenDigest } from "./src/clientConfig.ts";
12
import * as RelayDb from "./src/db.ts";
13
import { RelayObservability } from "./src/observability.ts";
14
-import { ManagedEndpointZone, RelayApiZone } from "./src/zone.ts";
14
+import { isPreviewStage } from "./src/previewStages.ts";
15
+import { PreviewTunnelSweep, PreviewTunnelSweepProvider } from "./src/previewTunnelSweep.ts";
16
+import { ManagedEndpointZone, RelayApiZone, RelayDeploymentConfig } from "./src/zone.ts";
17
import * as RelayWorker from "./src/worker.ts";
18
19
export default Alchemy.Stack(
@@ -22,16 +24,26 @@ export default Alchemy.Stack(
24
Cloudflare.providers(),
25
Drizzle.providers(),
26
Planetscale.providers(),
27
+ PreviewTunnelSweepProvider(),
28
),
29
state: Cloudflare.state(),
30
},
31
Effect.gen(function* () {
32
+ const { stage } = yield* Alchemy.Stack;
33
const db = yield* RelayDb.PlanetscaleDatabase;
34
const hyperdrive = yield* RelayDb.RelayHyperdrive;
35
const managedEndpointZone = yield* ManagedEndpointZone.pipe(Effect.orDie);
36
const relayApiZone = yield* RelayApiZone.pipe(Effect.orDie);
37
const observability = yield* RelayObservability;
38
const api = yield* RelayWorker.Api;
39
+ if (isPreviewStage(stage)) {
40
+ const { managedEndpointZoneName } = yield* RelayDeploymentConfig;
41
+ yield* PreviewTunnelSweep("PreviewTunnelSweep", {
42
+ stage,
43
+ tunnelZoneName: managedEndpointZoneName,
44
+ workerName: api.workerName,
45
+ });
46
+ }
47
yield* PublishClientConfig({
48
url: api.url,
49
mobileTracingUrl: observability.traces.otelTracesEndpoint,
infra/relay/src/previewStages.test.ts
new
+60
@@ -0,0 +1,60 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import {
4
+ isPreviewStage,
5
+ isPreviewTunnelName,
6
+ isPreviewTunnelRecordName,
7
+ previewSweepTargets,
8
+ tunnelCnameContent,
9
+} from "./previewStages.ts";
10
+
11
+const KEY = "0123456789abcdef";
12
+
13
+describe("preview stages", () => {
14
+ it("accepts only pull-request stages", () => {
15
+ expect(isPreviewStage("pr-42")).toBe(true);
16
+ expect(isPreviewStage("prod")).toBe(false);
17
+ expect(isPreviewStage("dev_julius")).toBe(false);
18
+ expect(isPreviewStage("pr-0")).toBe(false);
19
+ expect(isPreviewStage("pr-42/../prod")).toBe(false);
20
+ });
21
+
22
+ it("matches only tunnels of the exact stage", () => {
23
+ expect(isPreviewTunnelName(`t3coderelay-managedendpoint-pr-42-${KEY}`, "pr-42")).toBe(true);
24
+ expect(isPreviewTunnelName(`t3coderelay-managedendpoint-pr-42-${KEY}`, "pr-4")).toBe(false);
25
+ expect(isPreviewTunnelName(`t3coderelay-managedendpoint-prod-${KEY}`, "pr-42")).toBe(false);
26
+ expect(isPreviewTunnelName(`t3coderelay-managedendpoint-pr-42-xyz`, "pr-42")).toBe(false);
27
+ });
28
+
29
+ it("matches only hostnames of the exact stage under the tunnel zone", () => {
30
+ const zone = "tunnels.example.com";
31
+ expect(isPreviewTunnelRecordName(`pr-42-${KEY}.${zone}`, "pr-42", zone)).toBe(true);
32
+ expect(isPreviewTunnelRecordName(`PR-42-${KEY}.Tunnels.example.com`, "pr-42", zone)).toBe(true);
33
+ expect(isPreviewTunnelRecordName(`pr-4-${KEY}.${zone}`, "pr-42", zone)).toBe(false);
34
+ expect(isPreviewTunnelRecordName(`pr-42-${KEY}.other.com`, "pr-42", zone)).toBe(false);
35
+ expect(isPreviewTunnelRecordName(`relay.${zone}`, "pr-42", zone)).toBe(false);
36
+ });
37
+
38
+ it("targets only this stage's tunnels and the records that point at them", () => {
39
+ const zone = "tunnels.example.com";
40
+ const mine = `t3coderelay-managedendpoint-pr-42-${KEY}`;
41
+ const otherStage = `t3coderelay-managedendpoint-pr-7-${KEY}`;
42
+ const otherKey = "fedcba9876543210";
43
+ const targets = previewSweepTargets({
44
+ stage: "pr-42",
45
+ tunnelZoneName: zone,
46
+ tunnels: [
47
+ { id: "t-mine", name: mine },
48
+ { id: "t-other", name: otherStage },
49
+ ],
50
+ records: [
51
+ { id: "r-mine", name: `pr-42-${KEY}.${zone}`, content: tunnelCnameContent("t-mine") },
52
+ { id: "r-other", name: `pr-7-${KEY}.${zone}`, content: tunnelCnameContent("t-other") },
53
+ // Right label, but it targets a tunnel outside this sweep.
54
+ { id: "r-stranger", name: `pr-42-${otherKey}.${zone}`, content: "x.cfargotunnel.com" },
55
+ ],
56
+ });
57
+ expect(targets.tunnels.map((tunnel) => tunnel.id)).toEqual(["t-mine"]);
58
+ expect(targets.records.map((record) => record.id)).toEqual(["r-mine"]);
59
+ });
60
+});
infra/relay/src/previewStages.ts
new
+74
@@ -0,0 +1,74 @@
1
+import {
2
+ MANAGED_ENDPOINT_KEY_PATTERN,
3
+ managedEndpointTunnelNamePrefix,
4
+} from "./deploymentConfig.ts";
5
+
6
+// Only pull-request stages may be torn down by the cleanup job. Anchoring the
7
+// pattern keeps `prod`, personal `dev_<user>` stages, and `pr-0` out of reach.
8
+const PREVIEW_STAGE_PATTERN = /^pr-[1-9][0-9]*$/u;
9
+
10
+export function isPreviewStage(stage: string): boolean {
11
+ return PREVIEW_STAGE_PATTERN.test(stage);
12
+}
13
+
14
+// The prefix ends with a dash, so stage `pr-4` never matches tunnels of `pr-42`.
15
+export function isPreviewTunnelName(name: string, stage: string): boolean {
16
+ if (!isPreviewStage(stage)) return false;
17
+ const prefix = managedEndpointTunnelNamePrefix(stage);
18
+ return name.startsWith(prefix) && MANAGED_ENDPOINT_KEY_PATTERN.test(name.slice(prefix.length));
19
+}
20
+
21
+// Managed endpoint hostnames are `<stage>-<endpoint key>.<tunnel zone>`.
22
+export function isPreviewTunnelRecordName(
23
+ recordName: string,
24
+ stage: string,
25
+ tunnelZoneName: string,
26
+): boolean {
27
+ if (!isPreviewStage(stage)) return false;
28
+ const name = recordName.toLowerCase();
29
+ const suffix = `.${tunnelZoneName.trim().toLowerCase()}`;
30
+ if (!name.endsWith(suffix)) return false;
31
+ const label = name.slice(0, -suffix.length);
32
+ const labelPrefix = `${stage}-`;
33
+ return (
34
+ label.startsWith(labelPrefix) &&
35
+ MANAGED_ENDPOINT_KEY_PATTERN.test(label.slice(labelPrefix.length))
36
+ );
37
+}
38
+
39
+export function tunnelCnameContent(tunnelId: string): string {
40
+ return `${tunnelId}.cfargotunnel.com`;
41
+}
42
+
43
+export interface SweepTunnel {
44
+ readonly id: string;
45
+ readonly name?: string | null | undefined;
46
+}
47
+
48
+export interface SweepRecord {
49
+ readonly id: string;
50
+ readonly name: string;
51
+ readonly content?: string | null | undefined;
52
+}
53
+
54
+// Records are matched through the tunnel they point at, not just by name, so a
55
+// record that happens to share the label is never deleted unless it targets one
56
+// of this stage's tunnels.
57
+export function previewSweepTargets(input: {
58
+ readonly stage: string;
59
+ readonly tunnelZoneName: string;
60
+ readonly tunnels: ReadonlyArray<SweepTunnel>;
61
+ readonly records: ReadonlyArray<SweepRecord>;
62
+}): { readonly tunnels: ReadonlyArray<SweepTunnel>; readonly records: ReadonlyArray<SweepRecord> } {
63
+ const tunnels = input.tunnels.filter(
64
+ (tunnel) => tunnel.name != null && isPreviewTunnelName(tunnel.name, input.stage),
65
+ );
66
+ const tunnelContents = new Set(tunnels.map((tunnel) => tunnelCnameContent(tunnel.id)));
67
+ const records = input.records.filter(
68
+ (record) =>
69
+ isPreviewTunnelRecordName(record.name, input.stage, input.tunnelZoneName) &&
70
+ record.content != null &&
71
+ tunnelContents.has(record.content),
72
+ );
73
+ return { tunnels, records };
74
+}
infra/relay/src/previewTunnelSweep.test.ts
new
+102
@@ -0,0 +1,102 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as Exit from "effect/Exit";
4
+import * as Layer from "effect/Layer";
5
+import * as Redacted from "effect/Redacted";
6
+import * as HttpClient from "effect/http/HttpClient";
7
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
8
+
9
+import { sweepPreviewStage } from "./previewTunnelSweep.ts";
10
+
11
+const KEY = "0123456789abcdef";
12
+const TUNNEL_NAME = `t3coderelay-managedendpoint-pr-42-${KEY}`;
13
+
14
+// Answers the Cloudflare endpoints the sweep calls and records each request.
15
+const fakeCloudflare = (options: {
16
+ readonly tunnels: ReadonlyArray<{ readonly id: string; readonly name: string }>;
17
+ readonly zoneExists: boolean;
18
+ readonly deleteStatus?: number;
19
+}) => {
20
+ const seen: Array<string> = [];
21
+ const client = HttpClient.make((request) => {
22
+ const url = new URL(request.url);
23
+ seen.push(`${request.method} ${url.pathname}`);
24
+ const reply = (status: number, body: unknown) =>
25
+ Effect.succeed(
26
+ HttpClientResponse.fromWeb(
27
+ request,
28
+ new Response(JSON.stringify(body), {
29
+ status,
30
+ headers: { "content-type": "application/json" },
31
+ }),
32
+ ),
33
+ );
34
+ if (request.method === "DELETE") {
35
+ return reply(options.deleteStatus ?? 200, { success: true });
36
+ }
37
+ if (url.pathname.endsWith("/cfd_tunnel")) return reply(200, { result: options.tunnels });
38
+ if (url.pathname.endsWith("/zones")) {
39
+ return reply(200, { result: options.zoneExists ? [{ id: "zone-1" }] : [] });
40
+ }
41
+ if (url.pathname.endsWith("/dns_records")) return reply(200, { result: [] });
42
+ return reply(404, {});
43
+ });
44
+ return { client, seen };
45
+};
46
+
47
+const sweep = (cloudflare: ReturnType<typeof fakeCloudflare>) =>
48
+ sweepPreviewStage({
49
+ stage: "pr-42",
50
+ tunnelZoneName: "tunnels.example.com",
51
+ accountId: "account-1",
52
+ token: Redacted.make("token"),
53
+ }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, cloudflare.client)));
54
+
55
+describe("sweepPreviewStage", () => {
56
+ it.effect("does not need the zone once no tunnels remain", () =>
57
+ Effect.gen(function* () {
58
+ const cloudflare = fakeCloudflare({ tunnels: [], zoneExists: false });
59
+ yield* sweep(cloudflare);
60
+ expect(cloudflare.seen.some((request) => request.includes("/zones"))).toBe(false);
61
+ }),
62
+ );
63
+
64
+ it.effect("removes tunnels even when their zone is already gone", () =>
65
+ Effect.gen(function* () {
66
+ const cloudflare = fakeCloudflare({
67
+ tunnels: [{ id: "tunnel-1", name: TUNNEL_NAME }],
68
+ zoneExists: false,
69
+ });
70
+ yield* sweep(cloudflare);
71
+ expect(cloudflare.seen).toContain(
72
+ "DELETE /client/v4/accounts/account-1/cfd_tunnel/tunnel-1/connections",
73
+ );
74
+ expect(cloudflare.seen).toContain("DELETE /client/v4/accounts/account-1/cfd_tunnel/tunnel-1");
75
+ expect(cloudflare.seen.some((request) => request.includes("/dns_records"))).toBe(false);
76
+ }),
77
+ );
78
+
79
+ it.effect("treats an already-deleted tunnel as swept", () =>
80
+ Effect.gen(function* () {
81
+ const cloudflare = fakeCloudflare({
82
+ tunnels: [{ id: "tunnel-1", name: TUNNEL_NAME }],
83
+ zoneExists: false,
84
+ deleteStatus: 404,
85
+ });
86
+ const exit = yield* Effect.exit(sweep(cloudflare));
87
+ expect(Exit.isSuccess(exit)).toBe(true);
88
+ }),
89
+ );
90
+
91
+ it.effect("fails when Cloudflare rate-limits a delete so the next run retries it", () =>
92
+ Effect.gen(function* () {
93
+ const cloudflare = fakeCloudflare({
94
+ tunnels: [{ id: "tunnel-1", name: TUNNEL_NAME }],
95
+ zoneExists: false,
96
+ deleteStatus: 429,
97
+ });
98
+ const exit = yield* Effect.exit(sweep(cloudflare));
99
+ expect(Exit.isFailure(exit)).toBe(true);
100
+ }),
101
+ );
102
+});
infra/relay/src/previewTunnelSweep.ts
new
+183
@@ -0,0 +1,183 @@
1
+import { Resource } from "alchemy";
2
+import * as Provider from "alchemy/Provider";
3
+import * as Config from "effect/Config";
4
+import * as Effect from "effect/Effect";
5
+import * as Redacted from "effect/Redacted";
6
+import * as Schema from "effect/Schema";
7
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
8
+import * as HttpClient from "effect/http/HttpClient";
9
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
10
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
11
+
12
+import { managedEndpointTunnelNamePrefix } from "./deploymentConfig.ts";
13
+import { isPreviewStage, previewSweepTargets } from "./previewStages.ts";
14
+
15
+// Managed endpoint tunnels and their CNAMEs are created by the Worker at
16
+// runtime, so Alchemy never tracks them and `alchemy destroy` leaves them behind.
17
+// This resource exists only so its delete runs during a preview stage's destroy.
18
+
19
+export interface PreviewTunnelSweepProps {
20
+ readonly stage: string;
21
+ readonly tunnelZoneName: string;
22
+ // Depending on the Worker makes Alchemy delete this sweep before the Worker,
23
+ // because dependents go first. A live Worker could create a tunnel during
24
+ // that gap; the relay accepts that window.
25
+ readonly workerName: string;
26
+}
27
+
28
+export interface PreviewTunnelSweepAttributes {
29
+ readonly stage: string;
30
+ readonly tunnelZoneName: string;
31
+ readonly workerName: string;
32
+}
33
+
34
+export type PreviewTunnelSweep = Resource<
35
+ "T3CodeRelay.PreviewTunnelSweep",
36
+ PreviewTunnelSweepProps,
37
+ PreviewTunnelSweepAttributes
38
+>;
39
+
40
+export const PreviewTunnelSweep = Resource<PreviewTunnelSweep>("T3CodeRelay.PreviewTunnelSweep");
41
+
42
+const API = "https://api.cloudflare.com/client/v4";
43
+const PAGE_SIZE = 100;
44
+
45
+const TunnelPage = Schema.Struct({
46
+ result: Schema.Array(
47
+ Schema.Struct({ id: Schema.String, name: Schema.optional(Schema.NullOr(Schema.String)) }),
48
+ ),
49
+});
50
+const ZonePage = Schema.Struct({ result: Schema.Array(Schema.Struct({ id: Schema.String })) });
51
+const DnsRecordPage = Schema.Struct({
52
+ result: Schema.Array(
53
+ Schema.Struct({
54
+ id: Schema.String,
55
+ name: Schema.String,
56
+ content: Schema.optional(Schema.NullOr(Schema.String)),
57
+ }),
58
+ ),
59
+});
60
+
61
+const collectPages = Effect.fn("PreviewTunnelSweep.collectPages")(function* <T, E, R>(
62
+ fetchPage: (page: number) => Effect.Effect<ReadonlyArray<T>, E, R>,
63
+) {
64
+ const items: Array<T> = [];
65
+ for (let page = 1; ; page += 1) {
66
+ const batch = yield* fetchPage(page);
67
+ items.push(...batch);
68
+ if (batch.length < PAGE_SIZE) return items;
69
+ }
70
+});
71
+
72
+// Idempotent: a second run lists nothing and deletes nothing.
73
+export const sweepPreviewStage = Effect.fn("PreviewTunnelSweep.sweep")(function* (input: {
74
+ readonly stage: string;
75
+ readonly tunnelZoneName: string;
76
+ readonly accountId: string;
77
+ readonly token: Redacted.Redacted<string>;
78
+}) {
79
+ const client = yield* HttpClient.HttpClient;
80
+ const send = (request: HttpClientRequest.HttpClientRequest) =>
81
+ request.pipe(
82
+ HttpClientRequest.bearerToken(Redacted.value(input.token)),
83
+ client.execute,
84
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
85
+ );
86
+ const getJson = <A, I>(url: string, params: Record<string, string>, schema: Schema.Codec<A, I>) =>
87
+ send(HttpClientRequest.get(url, { urlParams: params })).pipe(
88
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
89
+ );
90
+ // A 404 means the object is already gone, which is the outcome teardown wants.
91
+ // Any other failure, including 429, fails the step so the next run retries it.
92
+ const remove = (url: string) =>
93
+ HttpClientRequest.make("DELETE")(url).pipe(
94
+ HttpClientRequest.bearerToken(Redacted.value(input.token)),
95
+ client.execute,
96
+ Effect.flatMap((response) =>
97
+ response.status === 404
98
+ ? Effect.void
99
+ : HttpClientResponse.filterStatusOk(response).pipe(Effect.asVoid),
100
+ ),
101
+ );
102
+
103
+ const listedTunnels = yield* collectPages((page) =>
104
+ getJson(
105
+ `${API}/accounts/${input.accountId}/cfd_tunnel`,
106
+ {
107
+ is_deleted: "false",
108
+ include_prefix: managedEndpointTunnelNamePrefix(input.stage),
109
+ per_page: String(PAGE_SIZE),
110
+ page: String(page),
111
+ },
112
+ TunnelPage,
113
+ ).pipe(Effect.map((body) => body.result)),
114
+ );
115
+
116
+ // No tunnels means nothing to clean, so the zone is not needed and may be gone.
117
+ if (listedTunnels.length === 0) return;
118
+
119
+ const zone = yield* getJson(`${API}/zones`, { name: input.tunnelZoneName }, ZonePage);
120
+ const zoneId = zone.result[0]?.id;
121
+ // Without the zone there are no CNAMEs to remove, but the tunnels still must go.
122
+ const listedRecords =
123
+ zoneId === undefined
124
+ ? []
125
+ : yield* collectPages((page) =>
126
+ getJson(
127
+ `${API}/zones/${zoneId}/dns_records`,
128
+ { type: "CNAME", per_page: String(PAGE_SIZE), page: String(page) },
129
+ DnsRecordPage,
130
+ ).pipe(Effect.map((body) => body.result)),
131
+ );
132
+
133
+ const targets = previewSweepTargets({
134
+ stage: input.stage,
135
+ tunnelZoneName: input.tunnelZoneName,
136
+ tunnels: listedTunnels,
137
+ records: listedRecords,
138
+ });
139
+
140
+ // Records first, so no hostname points at a tunnel that is about to vanish.
141
+ if (zoneId !== undefined) {
142
+ for (const record of targets.records) {
143
+ yield* remove(`${API}/zones/${zoneId}/dns_records/${record.id}`);
144
+ }
145
+ }
146
+ // Cloudflare refuses to delete a tunnel that still has connectors attached.
147
+ for (const tunnel of targets.tunnels) {
148
+ yield* remove(`${API}/accounts/${input.accountId}/cfd_tunnel/${tunnel.id}/connections`);
149
+ yield* remove(`${API}/accounts/${input.accountId}/cfd_tunnel/${tunnel.id}`);
150
+ }
151
+});
152
+
153
+export const PreviewTunnelSweepProvider = () =>
154
+ Provider.succeed(
155
+ PreviewTunnelSweep,
156
+ PreviewTunnelSweep.Provider.of({
157
+ reconcile: ({ news }) =>
158
+ Effect.succeed({
159
+ stage: news.stage,
160
+ tunnelZoneName: news.tunnelZoneName,
161
+ workerName: news.workerName,
162
+ }),
163
+ // Nothing in Cloudflare is created for this resource, so there is nothing to list.
164
+ list: () => Effect.succeed([]),
165
+ delete: Effect.fn(function* ({ output }) {
166
+ // The sweep runs only on preview stages. This guard keeps a mistaken
167
+ // stage from reaching the production relay's tunnels.
168
+ if (!isPreviewStage(output.stage)) {
169
+ return yield* Effect.die(`Refusing to sweep non-preview stage '${output.stage}'`);
170
+ }
171
+ // Read from the environment, not the Cloudflare service, so the provider
172
+ // needs no extra service in its layer. CI sets both for the destroy step.
173
+ const accountId = yield* Config.String("CLOUDFLARE_ACCOUNT_ID");
174
+ const token = yield* Config.Redacted("CLOUDFLARE_API_TOKEN");
175
+ yield* sweepPreviewStage({
176
+ stage: output.stage,
177
+ tunnelZoneName: output.tunnelZoneName,
178
+ accountId,
179
+ token,
180
+ }).pipe(Effect.provide(FetchHttpClient.layer));
181
+ }),
182
+ }),
183
+ );