The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as cloudfront from "@distilled.cloud/aws/cloudfront"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { toWireSeconds } from "alchemy/Util/Duration"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import type * as Duration from "effect/Duration"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | |
| 12 | export class CachePolicyConflict extends Data.TaggedError("CachePolicyConflict")<{ |
| 13 | readonly message: string; |
| 14 | readonly cause?: unknown; |
| 15 | }> {} |
| 16 | |
| 17 | export class CachePolicyUnexpectedResponse extends Data.TaggedError( |
| 18 | "CachePolicyUnexpectedResponse", |
| 19 | )<{ |
| 20 | readonly message: string; |
| 21 | readonly cause?: unknown; |
| 22 | }> {} |
| 23 | |
| 24 | export interface CachePolicyProps { |
| 25 | /** |
| 26 | * Name of the cache policy. If omitted, a deterministic name is generated. |
| 27 | * |
| 28 | * Names must be unique per AWS account. Changing the name triggers |
| 29 | * a replacement. |
| 30 | */ |
| 31 | name?: string; |
| 32 | /** |
| 33 | * Optional comment describing the policy. |
| 34 | */ |
| 35 | comment?: string; |
| 36 | /** |
| 37 | * Minimum amount of time that objects stay in the cache (e.g. |
| 38 | * `"1 minute"` or `Duration.minutes(1)`; a bare number is milliseconds). |
| 39 | */ |
| 40 | minTTL: Duration.Input; |
| 41 | /** |
| 42 | * Default amount of time that objects stay in the cache when the origin |
| 43 | * does not send `Cache-Control` or `Expires` headers (e.g. `"1 hour"`). |
| 44 | */ |
| 45 | defaultTTL?: Duration.Input; |
| 46 | /** |
| 47 | * Maximum amount of time that objects stay in the cache (e.g. `"1 day"`). |
| 48 | */ |
| 49 | maxTTL?: Duration.Input; |
| 50 | /** |
| 51 | * Controls which request values become part of the cache key and which |
| 52 | * additional headers/cookies/query strings CloudFront forwards to the origin. |
| 53 | */ |
| 54 | parametersInCacheKeyAndForwardedToOrigin?: cloudfront.ParametersInCacheKeyAndForwardedToOrigin; |
| 55 | } |
| 56 | |
| 57 | export interface CachePolicy extends Resource< |
| 58 | "AWS.CloudFront.CachePolicy", |
| 59 | CachePolicyProps, |
| 60 | { |
| 61 | /** |
| 62 | * CloudFront-assigned cache policy identifier. |
| 63 | */ |
| 64 | cachePolicyId: string; |
| 65 | /** |
| 66 | * Name of the cache policy. |
| 67 | */ |
| 68 | name: string; |
| 69 | /** |
| 70 | * Most recent entity tag for update/delete operations. |
| 71 | */ |
| 72 | etag: string | undefined; |
| 73 | /** |
| 74 | * Current comment on the policy. |
| 75 | */ |
| 76 | comment: string | undefined; |
| 77 | /** |
| 78 | * Current minimum TTL. |
| 79 | */ |
| 80 | minTTL: number; |
| 81 | /** |
| 82 | * Current default TTL. |
| 83 | */ |
| 84 | defaultTTL: number | undefined; |
| 85 | /** |
| 86 | * Current maximum TTL. |
| 87 | */ |
| 88 | maxTTL: number | undefined; |
| 89 | /** |
| 90 | * Current cache-key/forwarded-value configuration. |
| 91 | */ |
| 92 | parametersInCacheKeyAndForwardedToOrigin: |
| 93 | | cloudfront.ParametersInCacheKeyAndForwardedToOrigin |
| 94 | | undefined; |
| 95 | }, |
| 96 | never, |
| 97 | Providers |
| 98 | > {} |
| 99 | |
| 100 | /** |
| 101 | * A CloudFront cache policy. |
| 102 | * |
| 103 | * Cache policies determine the values CloudFront includes in the cache key, |
| 104 | * the headers, cookies and query strings it forwards to the origin, and the |
| 105 | * TTL bounds for cached responses. Policies are referenced by ID on a |
| 106 | * Distribution's default behavior or per-path cache behaviors. |
| 107 | * |
| 108 | * For AWS-managed policies (CachingOptimized, CachingDisabled, |
| 109 | * AllViewerExceptHostHeader) reference them by ID via the constants in |
| 110 | * {@link ManagedPolicies} instead of creating a custom policy. |
| 111 | * ### Creating Cache Policies |
| 112 | * **Example:** Cache by query string and Authorization header |
| 113 | * ```typescript |
| 114 | * const cachePolicy = yield* CachePolicy("ApiCachePolicy", { |
| 115 | * comment: "Cache GETs by query string + Authorization", |
| 116 | * minTTL: 0, |
| 117 | * defaultTTL: "1 minute", |
| 118 | * maxTTL: "1 hour", |
| 119 | * parametersInCacheKeyAndForwardedToOrigin: { |
| 120 | * EnableAcceptEncodingGzip: true, |
| 121 | * EnableAcceptEncodingBrotli: true, |
| 122 | * HeadersConfig: { |
| 123 | * HeaderBehavior: "whitelist", |
| 124 | * Headers: { Quantity: 1, Items: ["Authorization"] }, |
| 125 | * }, |
| 126 | * CookiesConfig: { CookieBehavior: "none" }, |
| 127 | * QueryStringsConfig: { QueryStringBehavior: "all" }, |
| 128 | * }, |
| 129 | * }); |
| 130 | * ``` |
| 131 | * |
| 132 | * @resource |
| 133 | */ |
| 134 | export const CachePolicy = Resource<CachePolicy>("AWS.CloudFront.CachePolicy"); |
| 135 | |
| 136 | export const CachePolicyProvider = () => |
| 137 | Provider.effect( |
| 138 | CachePolicy, |
| 139 | Effect.gen(function* () { |
| 140 | const getById = Effect.fn(function* (id: string) { |
| 141 | const config = yield* cloudfront |
| 142 | .getCachePolicyConfig({ Id: id }) |
| 143 | .pipe(Effect.catchTag("NoSuchCachePolicy", () => Effect.undefined)); |
| 144 | if (!config?.CachePolicyConfig) return undefined; |
| 145 | return { config: config.CachePolicyConfig, etag: config.ETag }; |
| 146 | }); |
| 147 | |
| 148 | const getByName = Effect.fn(function* (name: string) { |
| 149 | const listed = yield* cloudfront.listCachePolicies({ Type: "custom" }); |
| 150 | const summary = listed.CachePolicyList?.Items?.find( |
| 151 | (item) => item.CachePolicy?.CachePolicyConfig?.Name === name, |
| 152 | ); |
| 153 | if (!summary?.CachePolicy?.Id) return undefined; |
| 154 | return yield* getById(summary.CachePolicy.Id).pipe( |
| 155 | Effect.map((found) => (found ? { id: summary.CachePolicy.Id, ...found } : undefined)), |
| 156 | ); |
| 157 | }); |
| 158 | |
| 159 | const buildConfig = ( |
| 160 | name: string, |
| 161 | props: CachePolicyProps, |
| 162 | ): cloudfront.CachePolicyConfig => ({ |
| 163 | Name: name, |
| 164 | Comment: props.comment, |
| 165 | MinTTL: toWireSeconds(props.minTTL)!, |
| 166 | DefaultTTL: toWireSeconds(props.defaultTTL), |
| 167 | MaxTTL: toWireSeconds(props.maxTTL), |
| 168 | ParametersInCacheKeyAndForwardedToOrigin: props.parametersInCacheKeyAndForwardedToOrigin, |
| 169 | }); |
| 170 | |
| 171 | const toAttrs = ( |
| 172 | id: string, |
| 173 | config: cloudfront.CachePolicyConfig, |
| 174 | etag: string | undefined, |
| 175 | ) => ({ |
| 176 | cachePolicyId: id, |
| 177 | name: config.Name, |
| 178 | etag, |
| 179 | comment: config.Comment, |
| 180 | minTTL: config.MinTTL, |
| 181 | defaultTTL: config.DefaultTTL, |
| 182 | maxTTL: config.MaxTTL, |
| 183 | parametersInCacheKeyAndForwardedToOrigin: config.ParametersInCacheKeyAndForwardedToOrigin, |
| 184 | }); |
| 185 | |
| 186 | return { |
| 187 | stables: ["cachePolicyId"], |
| 188 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 189 | if (!isResolved(news)) return undefined; |
| 190 | if ((yield* createName(id, olds ?? {})) !== (yield* createName(id, news))) { |
| 191 | return { action: "replace" } as const; |
| 192 | } |
| 193 | }), |
| 194 | read: Effect.fn(function* ({ id, olds, output }) { |
| 195 | if (output?.cachePolicyId) { |
| 196 | const found = yield* getById(output.cachePolicyId); |
| 197 | if (found) return toAttrs(output.cachePolicyId, found.config, found.etag); |
| 198 | } |
| 199 | const name = yield* createName(id, olds ?? {}); |
| 200 | const found = yield* getByName(name); |
| 201 | if (!found) return undefined; |
| 202 | return toAttrs(found.id, found.config, found.etag); |
| 203 | }), |
| 204 | // CloudFront is global (no region). `listCachePolicies` returns both |
| 205 | // AWS-managed and custom policies; we filter to `Type: "custom"` since |
| 206 | // those are the only ones we create/delete. The op is marker-paginated |
| 207 | // (no `.pages`), so we loop until `NextMarker` is exhausted and hydrate |
| 208 | // each summary's ETag via `getById` so every row matches read(). |
| 209 | list: () => |
| 210 | Effect.gen(function* () { |
| 211 | const items: ReturnType<typeof toAttrs>[] = []; |
| 212 | let marker: string | undefined = undefined; |
| 213 | do { |
| 214 | const listed: cloudfront.ListCachePoliciesResult = |
| 215 | yield* cloudfront.listCachePolicies({ |
| 216 | Type: "custom", |
| 217 | Marker: marker, |
| 218 | }); |
| 219 | for (const summary of listed.CachePolicyList?.Items ?? []) { |
| 220 | if (summary.Type !== "custom") continue; |
| 221 | const id = summary.CachePolicy?.Id; |
| 222 | const config = summary.CachePolicy?.CachePolicyConfig; |
| 223 | if (!id || !config) continue; |
| 224 | const found = yield* getById(id); |
| 225 | items.push(toAttrs(id, found?.config ?? config, found?.etag)); |
| 226 | } |
| 227 | marker = listed.CachePolicyList?.NextMarker; |
| 228 | } while (marker); |
| 229 | return items; |
| 230 | }), |
| 231 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 232 | const name = yield* createName(id, news); |
| 233 | |
| 234 | // Observe — locate the policy by id (cached on `output`) or by |
| 235 | // name. Trust observed cloud state, not stale `olds`. |
| 236 | let observed = output?.cachePolicyId |
| 237 | ? yield* getById(output.cachePolicyId).pipe( |
| 238 | Effect.map((found) => (found ? { id: output.cachePolicyId, ...found } : undefined)), |
| 239 | ) |
| 240 | : undefined; |
| 241 | if (!observed) { |
| 242 | observed = yield* getByName(name); |
| 243 | } |
| 244 | |
| 245 | // Ensure — create the policy if it's missing. Tolerate |
| 246 | // `CachePolicyAlreadyExists` as a race with a peer reconciler: |
| 247 | // re-read by name and continue with the sync path. |
| 248 | if (!observed) { |
| 249 | const created = yield* cloudfront |
| 250 | .createCachePolicy({ |
| 251 | CachePolicyConfig: buildConfig(name, news), |
| 252 | }) |
| 253 | .pipe( |
| 254 | Effect.catchTag("CachePolicyAlreadyExists", () => |
| 255 | getByName(name).pipe( |
| 256 | Effect.flatMap((existing) => |
| 257 | existing |
| 258 | ? Effect.succeed({ |
| 259 | CachePolicy: { |
| 260 | Id: existing.id, |
| 261 | LastModifiedTime: new Date(), |
| 262 | CachePolicyConfig: existing.config, |
| 263 | }, |
| 264 | ETag: existing.etag, |
| 265 | Location: undefined, |
| 266 | }) |
| 267 | : Effect.fail( |
| 268 | new CachePolicyConflict({ |
| 269 | message: `Cache policy '${name}' already exists but could not be recovered`, |
| 270 | }), |
| 271 | ), |
| 272 | ), |
| 273 | ), |
| 274 | ), |
| 275 | ); |
| 276 | if (!created.CachePolicy?.Id) { |
| 277 | return yield* new CachePolicyUnexpectedResponse({ |
| 278 | message: "createCachePolicy returned no identifier", |
| 279 | }); |
| 280 | } |
| 281 | yield* session.note(created.CachePolicy.Id); |
| 282 | return toAttrs( |
| 283 | created.CachePolicy.Id, |
| 284 | created.CachePolicy.CachePolicyConfig, |
| 285 | created.ETag, |
| 286 | ); |
| 287 | } |
| 288 | |
| 289 | // Sync — diff observed config against desired and patch via |
| 290 | // `updateCachePolicy` with the freshly observed ETag. |
| 291 | const desired = buildConfig(observed.config.Name, news); |
| 292 | const updated = yield* cloudfront.updateCachePolicy({ |
| 293 | Id: observed.id, |
| 294 | IfMatch: observed.etag, |
| 295 | CachePolicyConfig: desired, |
| 296 | }); |
| 297 | if (!updated.CachePolicy?.Id) { |
| 298 | return yield* new CachePolicyUnexpectedResponse({ |
| 299 | message: "updateCachePolicy returned no identifier", |
| 300 | }); |
| 301 | } |
| 302 | yield* session.note(observed.id); |
| 303 | return toAttrs( |
| 304 | updated.CachePolicy.Id, |
| 305 | updated.CachePolicy.CachePolicyConfig, |
| 306 | updated.ETag, |
| 307 | ); |
| 308 | }), |
| 309 | delete: Effect.fn(function* ({ output }) { |
| 310 | const current = yield* getById(output.cachePolicyId); |
| 311 | if (!current) return; |
| 312 | yield* cloudfront |
| 313 | .deleteCachePolicy({ |
| 314 | Id: output.cachePolicyId, |
| 315 | IfMatch: current.etag, |
| 316 | }) |
| 317 | .pipe(Effect.catchTag("NoSuchCachePolicy", () => Effect.void)); |
| 318 | }), |
| 319 | }; |
| 320 | }), |
| 321 | ); |
| 322 | |
| 323 | const createName = (id: string, props: CachePolicyProps) => |
| 324 | props.name |
| 325 | ? Effect.succeed(props.name) |
| 326 | : createPhysicalName({ id, maxLength: 128, lowercase: true }); |