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

main
ts 203 lines 7.96 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Cluster, ClusterPolicy } from "@alchemy.run/aws/DSQL";
3 // Internal to alchemy, so not exported.
4 import { withDsqlClient } from "@alchemy.run/aws/DSQL/Migrations";
5 import * as Drizzle from "@alchemy.run/drizzle";
6 import { expect } from "@alchemy.run/test";
7 import * as Test from "@alchemy.run/test/Alchemy";
8 import * as dsql from "@distilled.cloud/aws/dsql";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Layer from "effect/Layer";
12 import * as Path from "effect/Path";
13
14 const { test } = Test.make({
15 providers: Layer.mergeAll(AWS.providers(), Drizzle.providers()),
16 });
17
18 /** Docs-canonical policy: deny non-VPC connections. */
19 const vpcOnlyPolicy = (exceptions?: string[]) =>
20 JSON.stringify({
21 Version: "2012-10-17",
22 Statement: [
23 {
24 Sid: "DenyNonVpcConnect",
25 Effect: "Deny",
26 Principal: { AWS: "*" },
27 Action: ["dsql:DbConnect", "dsql:DbConnectAdmin"],
28 Resource: "*",
29 Condition: {
30 Null: { "aws:SourceVpc": "true" },
31 ...(exceptions ? { StringNotEquals: { "aws:PrincipalArn": exceptions } } : {}),
32 },
33 },
34 ],
35 });
36
37 const getCluster = (identifier: string) =>
38 dsql
39 .getCluster({ identifier })
40 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)));
41
42 test.provider(
43 "create, update deletion protection, delete DSQL cluster",
44 (stack) =>
45 Effect.gen(function* () {
46 yield* stack.destroy();
47
48 // create (deletion protection off for test economics)
49 const created = yield* stack.deploy(
50 Effect.gen(function* () {
51 return yield* Cluster("AppDb", {
52 tags: { app: "alchemy-test" },
53 });
54 }),
55 );
56
57 expect(created.clusterId).toBeDefined();
58 expect(created.clusterArn).toContain(`:cluster/${created.clusterId}`);
59 expect(["ACTIVE", "IDLE"]).toContain(created.status);
60 expect(created.endpoint).toContain(created.clusterId);
61 expect(created.deletionProtectionEnabled).toBe(false);
62
63 // out-of-band verification
64 const observed = yield* getCluster(created.clusterId);
65 expect(observed?.identifier).toEqual(created.clusterId);
66 expect(observed?.deletionProtectionEnabled).toBe(false);
67
68 // update: enable deletion protection
69 const updated = yield* stack.deploy(
70 Effect.gen(function* () {
71 return yield* Cluster("AppDb", {
72 deletionProtectionEnabled: true,
73 tags: { app: "alchemy-test" },
74 });
75 }),
76 );
77 expect(updated.clusterId).toEqual(created.clusterId);
78 const reobserved = yield* getCluster(created.clusterId);
79 expect(reobserved?.deletionProtectionEnabled).toBe(true);
80
81 // attach a resource-based cluster policy (singleton sub-resource)
82 const withPolicy = yield* stack.deploy(
83 Effect.gen(function* () {
84 const cluster = yield* Cluster("AppDb", {
85 deletionProtectionEnabled: true,
86 tags: { app: "alchemy-test" },
87 });
88 const policy = yield* ClusterPolicy("AppDbPolicy", {
89 clusterId: cluster.clusterId,
90 policy: vpcOnlyPolicy(),
91 });
92 return {
93 clusterId: cluster.clusterId,
94 policyVersion: policy.policyVersion,
95 };
96 }),
97 );
98 expect(withPolicy.clusterId).toEqual(created.clusterId);
99 expect(withPolicy.policyVersion).toBeDefined();
100
101 // out-of-band verification of the attached document
102 const attached = yield* dsql.getClusterPolicy({
103 identifier: created.clusterId,
104 });
105 expect(attached.policy).toContain("DenyNonVpcConnect");
106 expect(attached.policyVersion).toEqual(withPolicy.policyVersion);
107
108 // update the policy document in place (version bumps)
109 const policyUpdated = yield* stack.deploy(
110 Effect.gen(function* () {
111 const cluster = yield* Cluster("AppDb", {
112 deletionProtectionEnabled: true,
113 tags: { app: "alchemy-test" },
114 });
115 const policy = yield* ClusterPolicy("AppDbPolicy", {
116 clusterId: cluster.clusterId,
117 policy: vpcOnlyPolicy(["arn:aws:iam::123456789012:role/ExceptionRole"]),
118 });
119 return { policyVersion: policy.policyVersion };
120 }),
121 );
122 expect(policyUpdated.policyVersion).not.toEqual(withPolicy.policyVersion);
123 const reattached = yield* dsql.getClusterPolicy({
124 identifier: created.clusterId,
125 });
126 expect(reattached.policy).toContain("ExceptionRole");
127
128 // delete (provider disables deletion protection automatically)
129 yield* stack.destroy();
130 const gone = yield* getCluster(created.clusterId);
131 // A deleted DSQL cluster is either gone or reports DELETING/DELETED.
132 expect(gone === undefined || gone.status === "DELETING" || gone.status === "DELETED").toBe(
133 true,
134 );
135 }),
136 { tags: ["provider:aws", "provider:aws:dsql", "live"], timeout: 300_000 },
137 );
138
139 test.provider(
140 "applies Drizzle migrations on deploy, applies new ones in place, and rejects edited history",
141 (stack) =>
142 Effect.gen(function* () {
143 yield* stack.destroy();
144 const fs = yield* FileSystem.FileSystem;
145 const path = yield* Path.Path;
146 // Generate into a temp directory so the test never writes checked-in files.
147 const out = yield* fs.makeTempDirectoryScoped();
148 const schema = path.join(import.meta.dirname, "fixtures/migrations/schema.ts");
149 const deploy = Effect.gen(function* () {
150 const generated = yield* Drizzle.Schema("Schema", { schema, out, dialect: "postgres" });
151 return yield* Cluster("Database", { migrations: generated.out });
152 });
153 const query = (endpoint: string, sql: string) =>
154 withDsqlClient(endpoint, (client) => Effect.tryPromise(() => client.query(sql)));
155
156 const created = yield* stack.deploy(deploy);
157 const history = yield* query(created.endpoint, "SELECT name, hash FROM __alchemy_migrations");
158 expect(history.rows).toHaveLength(1);
159 // CREATE INDEX ran as CREATE INDEX ASYNC and was awaited.
160 const indexes = yield* query(
161 created.endpoint,
162 "SELECT indisvalid FROM pg_index WHERE indexrelid = 'users_email_idx'::regclass",
163 );
164 expect(indexes.rows[0].indisvalid).toBe(true);
165 yield* query(
166 created.endpoint,
167 "INSERT INTO users(id, email) VALUES ('00000000-0000-0000-0000-000000000001', 'test@example.com')",
168 );
169
170 // A new migration file at the same path updates the cluster in place
171 // and keeps existing rows.
172 const [first] = (yield* fs.readDirectory(out)).sort();
173 const next = path.join(out, "20990101000000_evolve");
174 yield* fs.makeDirectory(next);
175 yield* fs.writeFileString(
176 path.join(next, "migration.sql"),
177 `ALTER TABLE users ADD COLUMN nickname text;
178 ALTER TABLE users RENAME COLUMN email TO address;`,
179 );
180 const updated = yield* stack.deploy(deploy);
181 expect(updated.clusterId).toBe(created.clusterId);
182 const user = yield* query(updated.endpoint, "SELECT address, nickname FROM users");
183 expect(user.rows).toEqual([{ address: "test@example.com", nickname: null }]);
184 const after = yield* query(updated.endpoint, "SELECT name FROM __alchemy_migrations");
185 expect(after.rows).toHaveLength(2);
186
187 // Editing an applied migration fails the deploy instead of silently
188 // skipping it.
189 yield* fs.writeFileString(
190 path.join(out, first!, "migration.sql"),
191 "CREATE TABLE users (id uuid PRIMARY KEY);",
192 );
193 const failure = yield* stack.deploy(deploy).pipe(Effect.flip);
194 expect(String(failure)).toMatch(/changed|does not match/i);
195
196 yield* stack.destroy();
197 const gone = yield* getCluster(created.clusterId);
198 expect(gone === undefined || gone.status === "DELETING" || gone.status === "DELETED").toBe(
199 true,
200 );
201 }),
202 { tags: ["provider:aws", "provider:aws:dsql", "live"], timeout: 600_000 },
203 );