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, 04:45 UTC
| 1 | import * as cache from "@distilled.cloud/cloudflare/cache"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Predicate from "effect/Predicate"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { listAllZones } from "../Zone/lookup.ts"; |
| 12 | |
| 13 | const TypeId = "Cloudflare.Cache.OriginCloudRegion" as const; |
| 14 | type TypeId = typeof TypeId; |
| 15 | |
| 16 | /** |
| 17 | * The cloud vendor hosting an origin. Region identifiers are |
| 18 | * vendor-specific — the valid set for each vendor is returned by the |
| 19 | * `supported_regions` endpoint |
| 20 | * (`/zones/{zone_id}/cache/origin_cloud_regions/supported_regions`). |
| 21 | */ |
| 22 | export type OriginCloudRegionVendor = "aws" | "azure" | "gcp" | "oci"; |
| 23 | |
| 24 | export interface OriginCloudRegionProps { |
| 25 | /** |
| 26 | * Zone the mapping belongs to. Stable — moving the mapping to a |
| 27 | * different zone triggers a replacement. |
| 28 | */ |
| 29 | zoneId: string; |
| 30 | /** |
| 31 | * Origin IP address (IPv4 or IPv6) the mapping applies to. The IP is the |
| 32 | * mapping's identity within the zone, so changing it triggers a |
| 33 | * replacement. |
| 34 | * |
| 35 | * Cloudflare normalizes the IP to canonical form before storage |
| 36 | * (RFC 5952 for IPv6) — supply IPv6 addresses in canonical form so the |
| 37 | * stored identity matches the prop. |
| 38 | */ |
| 39 | ip: string; |
| 40 | /** |
| 41 | * Cloud vendor hosting the origin. Mutable — patched in place. |
| 42 | */ |
| 43 | vendor: OriginCloudRegionVendor; |
| 44 | /** |
| 45 | * Cloud vendor region identifier, e.g. `us-east-1` for `aws`. Must be a |
| 46 | * valid region for the specified vendor (see the vendor's entry in the |
| 47 | * `supported_regions` endpoint). Mutable — patched in place. |
| 48 | */ |
| 49 | region: string; |
| 50 | } |
| 51 | |
| 52 | export interface OriginCloudRegionAttributes { |
| 53 | /** Zone the mapping belongs to. */ |
| 54 | zoneId: string; |
| 55 | /** Canonicalized origin IP the mapping applies to. */ |
| 56 | originIp: string; |
| 57 | /** Cloud vendor hosting the origin. */ |
| 58 | vendor: string; |
| 59 | /** Cloud vendor region identifier. */ |
| 60 | region: string; |
| 61 | /** When the mapping was last modified, if Cloudflare reports it. */ |
| 62 | modifiedOn: string | undefined; |
| 63 | } |
| 64 | |
| 65 | export type OriginCloudRegion = Resource< |
| 66 | TypeId, |
| 67 | OriginCloudRegionProps, |
| 68 | OriginCloudRegionAttributes, |
| 69 | never, |
| 70 | Providers |
| 71 | >; |
| 72 | |
| 73 | /** |
| 74 | * An origin cloud-region mapping of a Cloudflare zone |
| 75 | * (`/zones/{zone_id}/cache/origin_cloud_regions`). |
| 76 | * |
| 77 | * The mapping tells Cloudflare which public-cloud vendor region hosts a |
| 78 | * given origin IP, letting Tiered Cache pick an upper-tier data center |
| 79 | * close to the origin for better cache-fill performance. |
| 80 | * |
| 81 | * A mapping's identity is its origin IP within the zone — changing `ip` |
| 82 | * (or `zoneId`) triggers a replacement, while `vendor` and `region` are |
| 83 | * patched in place. Mappings carry no ownership markers: when there is no |
| 84 | * prior state, `read` reports an existing mapping for the same IP as |
| 85 | * `Unowned`, so the engine refuses to take it over unless `--adopt` |
| 86 | * (or `adopt(true)`) is set. |
| 87 | * ### Mapping origins to cloud regions |
| 88 | * **Example:** Map an origin IP to an AWS region |
| 89 | * ```typescript |
| 90 | * const zone = yield* Cloudflare.Zone.Zone("Site", { name: "example.com" }); |
| 91 | * |
| 92 | * yield* Cloudflare.Cache.OriginCloudRegion("ApiOrigin", { |
| 93 | * zoneId: zone.zoneId, |
| 94 | * ip: "192.0.2.10", |
| 95 | * vendor: "aws", |
| 96 | * region: "us-east-1", |
| 97 | * }); |
| 98 | * ``` |
| 99 | * |
| 100 | * **Example:** Map several origins of the same zone |
| 101 | * ```typescript |
| 102 | * // One resource per origin IP — the IP is the mapping's identity. |
| 103 | * yield* Cloudflare.Cache.OriginCloudRegion("UsOrigin", { |
| 104 | * zoneId: zone.zoneId, |
| 105 | * ip: "192.0.2.10", |
| 106 | * vendor: "gcp", |
| 107 | * region: "us-central1", |
| 108 | * }); |
| 109 | * yield* Cloudflare.Cache.OriginCloudRegion("EuOrigin", { |
| 110 | * zoneId: zone.zoneId, |
| 111 | * ip: "192.0.2.20", |
| 112 | * vendor: "gcp", |
| 113 | * region: "europe-west1", |
| 114 | * }); |
| 115 | * ``` |
| 116 | * |
| 117 | * @see https://developers.cloudflare.com/cache/how-to/tiered-cache/ |
| 118 | * |
| 119 | * @resource |
| 120 | * @product Cache |
| 121 | * @category Performance & Reliability |
| 122 | */ |
| 123 | export const OriginCloudRegion = Resource<OriginCloudRegion>(TypeId); |
| 124 | |
| 125 | /** |
| 126 | * Returns true if the given value is an OriginCloudRegion resource. |
| 127 | */ |
| 128 | export const isOriginCloudRegion = (value: unknown): value is OriginCloudRegion => |
| 129 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 130 | |
| 131 | /** |
| 132 | * Compare two origin IPs for identity. Cloudflare canonicalizes stored IPs |
| 133 | * (lowercased hex groups for IPv6 per RFC 5952), so a case-insensitive |
| 134 | * compare covers the common canonical-vs-uppercase drift without trying to |
| 135 | * re-implement full RFC 5952 normalization. |
| 136 | */ |
| 137 | const sameIp = (a: string, b: string): boolean => a.trim().toLowerCase() === b.trim().toLowerCase(); |
| 138 | |
| 139 | export const OriginCloudRegionProvider = () => |
| 140 | Provider.succeed(OriginCloudRegion, { |
| 141 | stables: ["zoneId", "originIp"], |
| 142 | |
| 143 | list: Effect.fn(function* () { |
| 144 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 145 | // Mappings live inside a zone (`/zones/{zone_id}/origin/cloud_regions`) |
| 146 | // with no account-wide list — enumerate every zone, then list its |
| 147 | // mappings and flatten. A zone may have zero mappings. |
| 148 | const allZones = yield* listAllZones(accountId); |
| 149 | const rows = yield* Effect.forEach( |
| 150 | allZones.map((zone) => zone.id), |
| 151 | (zoneId) => |
| 152 | cache.listOriginCloudRegions.pages({ zoneId }).pipe( |
| 153 | Stream.runCollect, |
| 154 | Effect.map((chunk) => |
| 155 | Array.from(chunk).flatMap((page) => |
| 156 | (page.result ?? []).map((mapping) => toAttributes(zoneId, mapping)), |
| 157 | ), |
| 158 | ), |
| 159 | // Plan-gated / deleted zones reject the route; skip them. |
| 160 | Effect.catchTag("InvalidRoute", () => Effect.succeed([])), |
| 161 | ), |
| 162 | { concurrency: 10 }, |
| 163 | ); |
| 164 | return rows.flat(); |
| 165 | }), |
| 166 | |
| 167 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 168 | if (!isResolved(news)) return undefined; |
| 169 | // The IP is the mapping's identity — changing it replaces. Prefer the |
| 170 | // canonicalized IP cached on output; fall back to resolved old props. |
| 171 | const oldIp = |
| 172 | output?.originIp ?? (olds !== undefined && isResolved(olds) ? olds.ip : undefined); |
| 173 | if (oldIp !== undefined && !sameIp(oldIp, news.ip)) { |
| 174 | return { action: "replace" } as const; |
| 175 | } |
| 176 | const oldZoneId = |
| 177 | output?.zoneId ?? (olds !== undefined && isResolved(olds) ? olds.zoneId : undefined); |
| 178 | if (oldZoneId !== undefined && oldZoneId !== news.zoneId) { |
| 179 | return { action: "replace" } as const; |
| 180 | } |
| 181 | return undefined; |
| 182 | }), |
| 183 | |
| 184 | read: Effect.fn(function* ({ output, olds }) { |
| 185 | const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined); |
| 186 | const ip = output?.originIp ?? olds?.ip; |
| 187 | if (!zoneId || !ip) return undefined; |
| 188 | |
| 189 | const observed = yield* getMapping(zoneId, ip); |
| 190 | if (observed === undefined) return undefined; |
| 191 | |
| 192 | // Owned path: we have persisted attributes for this mapping. |
| 193 | if (output?.originIp) return observed; |
| 194 | |
| 195 | // Adoption path: a mapping for this IP already exists but carries no |
| 196 | // ownership markers — brand it `Unowned` so the engine refuses to |
| 197 | // take over unless `adopt` is set. |
| 198 | return Unowned(observed); |
| 199 | }), |
| 200 | |
| 201 | reconcile: Effect.fn(function* ({ news, output }) { |
| 202 | // Inputs have been resolved to concrete strings by Plan. |
| 203 | const zoneId = news.zoneId as string; |
| 204 | // `output` caches the canonicalized IP; fall back to the prop. |
| 205 | const ip = output?.originIp ?? news.ip; |
| 206 | |
| 207 | // 1. Observe — cloud state is authoritative; a cached output is only |
| 208 | // a hint and the mapping may be gone. |
| 209 | const observed = yield* getMapping(zoneId, ip); |
| 210 | |
| 211 | // 2. Ensure + sync in one step — the endpoint is a true PUT upsert |
| 212 | // (`PUT /origin/cloud_regions/{origin_ip}`), so a missing mapping |
| 213 | // and a drifted mapping converge through the same call. Skip the |
| 214 | // API entirely on a no-op. |
| 215 | if ( |
| 216 | observed !== undefined && |
| 217 | observed.vendor === news.vendor && |
| 218 | observed.region === news.region |
| 219 | ) { |
| 220 | return observed; |
| 221 | } |
| 222 | const upserted = yield* cache.putOriginCloudRegion({ |
| 223 | zoneId, |
| 224 | // Path param and body `origin_ip` must match or Cloudflare rejects |
| 225 | // the request with a 400. |
| 226 | originIP: ip, |
| 227 | originIp: ip, |
| 228 | vendor: news.vendor, |
| 229 | region: news.region, |
| 230 | }); |
| 231 | return toAttributes(zoneId, upserted); |
| 232 | }), |
| 233 | |
| 234 | delete: Effect.fn(function* ({ output }) { |
| 235 | // Idempotent — the mapping may already be gone (typed not-found), or |
| 236 | // the zone itself may have been deleted out-of-band (InvalidRoute). |
| 237 | yield* cache |
| 238 | .deleteOriginCloudRegion({ |
| 239 | zoneId: output.zoneId, |
| 240 | originIP: output.originIp, |
| 241 | }) |
| 242 | .pipe( |
| 243 | Effect.catchTags({ |
| 244 | OriginCloudRegionNotFound: () => Effect.void, |
| 245 | InvalidRoute: () => Effect.void, |
| 246 | }), |
| 247 | ); |
| 248 | }), |
| 249 | }); |
| 250 | |
| 251 | /** |
| 252 | * Read a mapping by IP, mapping "gone" (typed `OriginCloudRegionNotFound`, |
| 253 | * or `InvalidRoute` when the zone itself no longer routes) to `undefined`. |
| 254 | */ |
| 255 | const getMapping = (zoneId: string, ip: string) => |
| 256 | cache.getOriginCloudRegion({ zoneId, originIP: ip }).pipe( |
| 257 | Effect.map((response): OriginCloudRegionAttributes | undefined => |
| 258 | toAttributes(zoneId, response), |
| 259 | ), |
| 260 | Effect.catchTag("OriginCloudRegionNotFound", () => Effect.undefined), |
| 261 | ); |
| 262 | |
| 263 | const toAttributes = ( |
| 264 | zoneId: string, |
| 265 | response: |
| 266 | | cache.GetOriginCloudRegionResponse |
| 267 | | cache.PutOriginCloudRegionResponse |
| 268 | | cache.ListOriginCloudRegionsResponse["result"][number], |
| 269 | ): OriginCloudRegionAttributes => ({ |
| 270 | zoneId, |
| 271 | originIp: response.originIp, |
| 272 | vendor: response.vendor, |
| 273 | region: response.region, |
| 274 | modifiedOn: response.modifiedOn ?? undefined, |
| 275 | }); |