@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 301 lines 10.4 KB
Raw
1 import * as cloudConnector from "@distilled.cloud/cloudflare/cloud-connector";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { listAllZones } from "../Zone/lookup.ts";
11
12 const TypeId = "Cloudflare.CloudConnector.Rules" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * The cloud-provider object storage a Cloud Connector rule routes matching
17 * traffic to.
18 */
19 export type CloudConnectorProvider = "aws_s3" | "cloudflare_r2" | "gcp_storage" | "azure_storage";
20
21 /**
22 * A single Cloud Connector rule routing matching traffic directly to a
23 * cloud-provider object-storage bucket.
24 */
25 export interface Rule {
26 /**
27 * The cloud provider hosting the bucket the rule routes traffic to.
28 */
29 provider: CloudConnectorProvider;
30 /**
31 * Cloudflare Rules language expression selecting the traffic the rule
32 * applies to, e.g. `http.request.uri.path wildcard "/images/*"`.
33 */
34 expression: string;
35 /**
36 * Host of the target bucket — e.g. `mybucket.s3.amazonaws.com` for S3,
37 * or an R2 bucket's public host. Accepts an `Input` so it can reference
38 * another resource's output (commonly an `Bucket`).
39 */
40 host: string;
41 /**
42 * Whether the rule is enabled.
43 * @default true
44 */
45 enabled?: boolean;
46 /**
47 * Informative description of the rule.
48 */
49 description?: string;
50 }
51
52 export interface RulesProps {
53 /**
54 * Zone the rules apply to. Stable — changing the zone triggers
55 * replacement.
56 */
57 zoneId: string;
58 /**
59 * Ordered list of Cloud Connector rules. The whole list is owned by
60 * this resource and replaced atomically on every change — rules
61 * managed elsewhere in the zone will be overwritten on deploy.
62 */
63 rules: Rule[];
64 }
65
66 /**
67 * A Cloud Connector rule as Cloudflare reports it.
68 */
69 export interface RuleAttribute {
70 /** Cloudflare-assigned identifier of the rule. */
71 id: string | undefined;
72 /** The cloud provider the rule routes traffic to. */
73 provider: string;
74 /** Rules language expression selecting matching traffic. */
75 expression: string;
76 /** Host of the target bucket. */
77 host: string;
78 /** Whether the rule is enabled. */
79 enabled: boolean;
80 /** Informative description of the rule. */
81 description: string | undefined;
82 }
83
84 export interface RulesAttributes {
85 /** Zone that owns the rule list. */
86 zoneId: string;
87 /** The ordered rule list as Cloudflare reports it. */
88 rules: RuleAttribute[];
89 }
90
91 export type Rules = Resource<TypeId, RulesProps, RulesAttributes, never, Providers>;
92
93 /**
94 * The ordered list of Cloud Connector rules for a Cloudflare zone.
95 *
96 * Cloud Connector routes matching traffic directly from Cloudflare's edge
97 * to a cloud-provider object-storage bucket (Cloudflare R2, Amazon S3,
98 * Google Cloud Storage, or Azure Blob Storage) without an origin server.
99 * Each rule pairs a Rules-language expression with the target bucket host.
100 *
101 * The zone has exactly one rule list — the API only supports replacing the
102 * whole list — so this resource owns it in its entirety (PUT-replace
103 * semantics) and there should be at most one `Rules`
104 * resource per zone. Destroying the resource clears the list.
105 *
106 * Safety: when there is no prior state and the zone already has a
107 * non-empty rule list, `read` reports it as `Unowned` and the engine
108 * refuses to take it over unless `--adopt` (or `adopt(true)`) is set.
109 *
110 * Note: Cloud Connector only takes effect on proxied (orange-cloud) DNS
111 * records, and the number of rules per zone is plan-limited.
112 * ### Routing to object storage
113 * **Example:** Serve a path prefix from an S3 bucket
114 * ```typescript
115 * yield* Cloudflare.CloudConnector.Rules("Rules", {
116 * zoneId: zone.zoneId,
117 * rules: [
118 * {
119 * provider: "aws_s3",
120 * expression: 'http.request.uri.path wildcard "/images/*"',
121 * host: "mybucket.s3.amazonaws.com",
122 * description: "serve images from S3",
123 * },
124 * ],
125 * });
126 * ```
127 *
128 * **Example:** Serve static assets from an R2 bucket
129 * ```typescript
130 * const bucket = yield* Cloudflare.R2.Bucket("Assets", {});
131 *
132 * yield* Cloudflare.CloudConnector.Rules("Rules", {
133 * zoneId: zone.zoneId,
134 * rules: [
135 * {
136 * provider: "cloudflare_r2",
137 * expression: 'http.request.uri.path wildcard "/assets/*"',
138 * // public R2 bucket host (r2.dev or a custom domain)
139 * host: publicBucketHost,
140 * description: "static assets from R2",
141 * },
142 * ],
143 * });
144 * ```
145 *
146 * @see https://developers.cloudflare.com/rules/cloud-connector/
147 *
148 * @resource
149 * @product Cloud Connector
150 * @category Rules & Configuration
151 */
152 export const Rules = Resource<Rules>(TypeId);
153
154 /**
155 * Returns true if the given value is a Rules resource.
156 */
157 export const isRules = (value: unknown): value is Rules =>
158 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
159
160 export const RulesProvider = () =>
161 Provider.succeed(Rules, {
162 stables: ["zoneId"],
163
164 list: Effect.fn(function* () {
165 const { accountId } = yield* yield* CloudflareEnvironment;
166 // No account-wide API for Cloud Connector rules — the rule list is
167 // a per-zone singleton, so enumerate every zone and read its list.
168 const zones = yield* listAllZones(accountId);
169 const rows = yield* Effect.forEach(
170 zones,
171 (zone) =>
172 listObservedRules(zone.id).pipe(
173 Effect.map((rules): RulesAttributes | undefined =>
174 // A zone with no rules has nothing to manage — same as
175 // `read` returning `undefined` for an empty list.
176 rules.length === 0 ? undefined : { zoneId: zone.id, rules },
177 ),
178 // Plan-gated zones reject the route; skip them.
179 Effect.catchTag("Forbidden", () => Effect.undefined),
180 ),
181 { concurrency: 10 },
182 );
183 return rows.filter((row): row is RulesAttributes => row !== undefined);
184 }),
185
186 diff: Effect.fn(function* ({ olds, news, output }) {
187 const o = olds as RulesProps;
188 const n = news as RulesProps;
189 // zoneId is the resource's identity; compare only once both sides
190 // are concrete.
191 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
192 if (typeof n.zoneId === "string" && oldZoneId !== undefined && oldZoneId !== n.zoneId) {
193 return { action: "replace" } as const;
194 }
195 }),
196
197 read: Effect.fn(function* ({ olds, output }) {
198 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
199 if (!zoneId) return undefined;
200 const observed = yield* listObservedRules(zoneId);
201 // An empty list means the resource doesn't exist — the API has no
202 // separate "created but empty" state.
203 if (observed.length === 0) return undefined;
204 const attrs: RulesAttributes = { zoneId, rules: observed };
205 // No prior state of our own but the zone already has rules — they
206 // may be managed by hand or by another tool. Refuse to take over
207 // unless adoption is explicitly allowed.
208 if (output === undefined) return Unowned(attrs);
209 return attrs;
210 }),
211
212 reconcile: Effect.fn(function* ({ news, output }) {
213 // Inputs have been resolved to concrete values by Plan.
214 const zoneId = (output?.zoneId ?? news.zoneId) as string;
215 const desired = news.rules.map((rule) => ({
216 provider: rule.provider,
217 expression: rule.expression,
218 host: rule.host as string,
219 enabled: rule.enabled ?? true,
220 description: rule.description,
221 }));
222
223 // Observe the live rule list and skip the PUT when it already
224 // matches the desired state (ignoring server-assigned rule ids).
225 const observed = yield* listObservedRules(zoneId);
226 if (!rulesEqual(desired, observed)) {
227 yield* cloudConnector.putRule({
228 zoneId,
229 rules: desired.map((rule) => ({
230 provider: rule.provider,
231 expression: rule.expression,
232 parameters: { host: rule.host },
233 enabled: rule.enabled,
234 description: rule.description,
235 })),
236 });
237 }
238
239 // Re-read so attributes carry Cloudflare's canonical view,
240 // including server-assigned rule ids.
241 const synced = yield* listObservedRules(zoneId);
242 return { zoneId, rules: synced } satisfies RulesAttributes;
243 }),
244
245 delete: Effect.fn(function* ({ output }) {
246 // The API has no DELETE endpoint — clearing the list is a PUT with
247 // an empty rule array, which is naturally idempotent. A zone deleted
248 // out-of-band surfaces as InvalidRoute (Cloudflare code 7003) — the
249 // rules are gone with it.
250 yield* cloudConnector
251 .putRule({ zoneId: output.zoneId, rules: [] })
252 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
253 }),
254 });
255
256 const listObservedRules = (zoneId: string) =>
257 cloudConnector.listRules.items({ zoneId }).pipe(
258 Stream.runCollect,
259 Effect.map((chunk): RuleAttribute[] =>
260 Array.from(chunk).flatMap((rule) =>
261 rule.expression == null || rule.provider == null || rule.parameters?.host == null
262 ? []
263 : [
264 {
265 id: rule.id ?? undefined,
266 provider: rule.provider,
267 expression: rule.expression,
268 host: rule.parameters.host,
269 enabled: rule.enabled ?? true,
270 description: rule.description ?? undefined,
271 },
272 ],
273 ),
274 ),
275 // A zone that has never had Cloud Connector rules configured reports
276 // "could not find entrypoint ruleset" (code 10003) — that's just an
277 // empty list.
278 Effect.catchTag("CloudConnectorRulesNotFound", () => Effect.succeed([] as RuleAttribute[])),
279 );
280
281 const rulesEqual = (
282 desired: ReadonlyArray<{
283 provider: string;
284 expression: string;
285 host: string;
286 enabled: boolean;
287 description: string | undefined;
288 }>,
289 observed: ReadonlyArray<RuleAttribute>,
290 ): boolean =>
291 desired.length === observed.length &&
292 desired.every((d, i) => {
293 const o = observed[i];
294 return (
295 d.provider === o.provider &&
296 d.expression === o.expression &&
297 d.host === o.host &&
298 d.enabled === o.enabled &&
299 (d.description ?? undefined) === o.description
300 );
301 });