import { Region as AwsRegion } from "@distilled.cloud/aws/Region"; import * as kvs from "@distilled.cloud/aws/cloudfront-keyvaluestore"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Redacted from "effect/Redacted"; import * as Schedule from "effect/Schedule"; // CloudFront KeyValueStore APIs are only available from us-east-1, even when // the distribution using the store lives elsewhere. export const KVS_REGION = "us-east-1" as const; export const extractValue = (v: string | Redacted.Redacted): string => typeof v === "string" ? v : Redacted.value(v); export const withKvsRegion = (effect: Effect.Effect) => // The distilled Region service value is `Effect`, not a raw // string — providing a bare string makes the client `yield*` a string and // crash. Wrap in Effect.succeed (same as ACM/ECRPublic/WAFv2/GlobalAccelerator). effect.pipe(Effect.provideService(AwsRegion, Effect.succeed(KVS_REGION))); export const withKvsRegionFn = ( fn: (...args: Args) => Effect.Effect, ) => (...args: Args) => withKvsRegion(fn(...args)); const isKvsNotReady = (error: unknown) => { const tag = (error as { _tag?: string })._tag; return tag === "ResourceNotFoundException" || tag === "ConflictException"; }; const cappedKvsRetrySchedule = Schedule.max([ Schedule.exponential("100 millis"), Schedule.recurs(24), ]).pipe( Schedule.modifyDelay(({ duration }) => Effect.succeed( Duration.isGreaterThan(duration, Duration.seconds(2)) ? Duration.seconds(2) : duration, ), ), ); export const retryForKvsReadiness = (effect: Effect.Effect) => effect.pipe( Effect.retry({ while: isKvsNotReady, schedule: cappedKvsRetrySchedule, }), ); export const getKvsEtag = Effect.fn(function* (store: string) { const response = yield* kvs.describeKeyValueStore({ KvsARN: store }); return response.ETag; }); export const isKvsPreconditionFailed = (err: kvs.ValidationException) => typeof err.message === "string" && err.message.includes("Pre-Condition failed");