1import * as Effect from "effect/Effect";
2import * as Layer from "effect/Layer";
3import * as Binding from "../../Binding.ts";
4import * as Output from "../../Output.ts";
5import { unpackEnvValue } from "../../RuntimeContext.ts";
6import { isBindingHost } from "../Lambda/Function.ts";
7import {
8 ConnectCacheCluster,
9 cacheClusterConnectEnvPrefix,
10 type ConnectCacheClusterOptions,
11} from "./ConnectCacheCluster.ts";
12import type { CacheCluster } from "./CacheCluster.ts";
13
14export const ConnectCacheClusterHttp = Layer.effect(
15 ConnectCacheCluster,
16 Effect.gen(function* () {
17 return Effect.fn(function* (
18 cluster: CacheCluster,
19 options?: ConnectCacheClusterOptions,
20 ) {
21 const prefix = cacheClusterConnectEnvPrefix(cluster.LogicalId);
22 if (!globalThis.__ALCHEMY_RUNTIME__) {
23 const host = yield* Binding.Host;
24 if (isBindingHost(host)) {
25 yield* host.bind`Allow(${host}, AWS.ElastiCache.ConnectCacheCluster(${cluster}))`(
26 {
27 env: {
28 [`${prefix}_ENDPOINTS`]: Output.map(
29 cluster.endpoints,
30 JSON.stringify,
31 ),
32 [`${prefix}_TLS`]: Output.map(
33 cluster.transitEncryptionEnabled,
34 (tls) => String(tls ?? false),
35 ),
36 },
37 ...(options?.subnetIds || options?.securityGroupIds
38 ? {
39 vpc: {
40 subnetIds: options?.subnetIds ?? [],
41 securityGroupIds: options?.securityGroupIds ?? [],
42 },
43 }
44 : {}),
45 },
46 );
47 }
48 }
49 return Effect.gen(function* () {
50 const endpoints = unpackEnvValue<
51 Array<{ address: string; port: number }>
52 >(process.env[`${prefix}_ENDPOINTS`]);
53 if (endpoints !== undefined) {
54 if (!endpoints.length) {
55 return yield* Effect.die(
56 `Memcached endpoints for '${cluster.LogicalId}' are not available`,
57 );
58 }
59 return {
60 endpoints,
61 tls: unpackEnvValue<boolean>(process.env[`${prefix}_TLS`]) ?? false,
62 };
63 }
64 const clusterEndpoints = yield* yield* cluster.endpoints;
65 if (!clusterEndpoints.length) {
66 return yield* Effect.die(
67 `Memcached endpoints for '${cluster.LogicalId}' are not available yet`,
68 );
69 }
70 return {
71 endpoints: clusterEndpoints,
72 tls: yield* yield* cluster.transitEncryptionEnabled,
73 };
74 });
75 });
76 }),
77);