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

main
ts 149 lines 6.01 KB
Raw
1 import * as redshift from "@distilled.cloud/aws/redshift";
2 import * as Output from "alchemy/Output";
3 import { toWireSeconds } from "alchemy/Util/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Redacted from "effect/Redacted";
7 import * as AWSBindings from "../AWSBindings.ts";
8 import { formatSqlConnectionUrl } from "../Connection/internal.ts";
9 import type { Cluster } from "./Cluster.ts";
10 import { Connect, connectEnvPrefix, type ConnectOptions } from "./Connect.ts";
11
12 const DEFAULT_PORT = 5439;
13
14 const unwrap = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
15 value === undefined ? undefined : Redacted.isRedacted(value) ? Redacted.value(value) : value;
16
17 /**
18 * SDK-backed implementation of {@link Connect}. Deploy half attaches the
19 * `redshift:GetClusterCredentials[WithIAM]` policy scoped to the cluster's
20 * `dbname`/`dbuser`/`dbgroup` ARNs and publishes
21 * `REDSHIFT_{LOGICAL_ID}_{HOST,PORT}` on the host Function; runtime half
22 * mints temporary credentials via the corresponding SDK operation and
23 * formats a pgwire connection URL.
24 */
25 export const ConnectHttp = Layer.effect(
26 Connect,
27 Effect.gen(function* () {
28 const bind = yield* AWSBindings.Bind;
29 const getClusterCredentials = yield* AWSBindings.withCredentials(
30 redshift.getClusterCredentials,
31 );
32 const getClusterCredentialsWithIAM = yield* AWSBindings.withCredentials(
33 redshift.getClusterCredentialsWithIAM,
34 );
35
36 return Effect.fn(function* (cluster: Cluster, options: ConnectOptions = {}) {
37 const ClusterIdentifier = yield* cluster.clusterIdentifier;
38 const Host = yield* cluster.endpointAddress;
39 const Port = yield* cluster.endpointPort;
40 const DbName = yield* cluster.dbName;
41
42 if (!globalThis.__ALCHEMY_RUNTIME__) {
43 // `arn:aws:redshift:{region}:{acct}` — the cluster ARN minus its
44 // `:cluster:{id}` suffix; base for the dbname/dbuser/dbgroup ARNs
45 // that scope the GetClusterCredentials* actions.
46 const arnBase = Output.map(cluster.clusterArn, (arn) =>
47 arn.slice(0, arn.lastIndexOf(":cluster:")),
48 );
49 const database = options.database ?? cluster.dbName;
50 const dbNameArn = Output.interpolate`${arnBase}:dbname:${cluster.clusterIdentifier}/${database}`;
51 const prefix = connectEnvPrefix(cluster.LogicalId);
52 // The binding id must be unique per credential strategy: a Function
53 // that connects to the same cluster both as its IAM identity and as
54 // a named database user needs BOTH policy statements, and binds that
55 // share an id collapse into one (the last one wins).
56 const strategy = options.dbUser !== undefined ? `, ${options.dbUser}` : "";
57 yield* bind`AWS.Redshift.Connect(${cluster}${strategy})`({
58 policyStatements:
59 options.dbUser !== undefined
60 ? [
61 {
62 Effect: "Allow" as const,
63 Action: [
64 "redshift:GetClusterCredentials",
65 ...(options.autoCreate ? ["redshift:CreateClusterUser"] : []),
66 ],
67 Resource: [
68 Output.interpolate`${arnBase}:dbuser:${cluster.clusterIdentifier}/${options.dbUser}`,
69 dbNameArn,
70 ],
71 },
72 ...(options.dbGroups && options.dbGroups.length > 0
73 ? [
74 {
75 Effect: "Allow" as const,
76 Action: ["redshift:JoinGroup"],
77 Resource: options.dbGroups.map(
78 (group) =>
79 Output.interpolate`${arnBase}:dbgroup:${cluster.clusterIdentifier}/${group}`,
80 ),
81 },
82 ]
83 : []),
84 ]
85 : [
86 {
87 Effect: "Allow" as const,
88 Action: ["redshift:GetClusterCredentialsWithIAM"],
89 Resource: [dbNameArn],
90 },
91 ],
92 env: {
93 [`${prefix}_HOST`]: cluster.endpointAddress,
94 // Lambda environment variables are strings — stringify the port.
95 [`${prefix}_PORT`]: Output.interpolate`${cluster.endpointPort}`,
96 },
97 });
98 }
99
100 return Effect.gen(function* () {
101 const clusterIdentifier = yield* ClusterIdentifier;
102 const host = yield* Host;
103 const port = (yield* Port) ?? DEFAULT_PORT;
104 const database = options.database ?? (yield* DbName);
105 if (!host) {
106 return yield* Effect.die(
107 `Redshift cluster endpoint for '${cluster.LogicalId}' is not available yet`,
108 );
109 }
110 const credentials =
111 options.dbUser !== undefined
112 ? yield* getClusterCredentials({
113 ClusterIdentifier: clusterIdentifier,
114 DbUser: options.dbUser,
115 DbName: database,
116 AutoCreate: options.autoCreate,
117 DbGroups: options.dbGroups,
118 DurationSeconds: toWireSeconds(options.duration),
119 })
120 : yield* getClusterCredentialsWithIAM({
121 ClusterIdentifier: clusterIdentifier,
122 DbName: database,
123 DurationSeconds: toWireSeconds(options.duration),
124 });
125 const username = unwrap(credentials.DbUser);
126 const rawPassword = unwrap(credentials.DbPassword);
127 const password = rawPassword === undefined ? undefined : Redacted.make(rawPassword);
128 const ssl = options.ssl ?? true;
129 return {
130 host,
131 port,
132 database,
133 username,
134 password,
135 ssl,
136 expiration: credentials.Expiration,
137 url: formatSqlConnectionUrl({
138 host,
139 port,
140 database,
141 username,
142 password,
143 ssl,
144 }),
145 };
146 });
147 });
148 }),
149 );