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

main
ts 429 lines 14 KB
Raw
1 import * as redis from "@distilled.cloud/gcp/redis_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const MAX_NAME_LENGTH = 63;
15
16 export type AclRule = {
17 /**
18 * Redis ACL username. For IAM auth this is an IAM user or service
19 * account; otherwise any Redis ACL username.
20 */
21 username?: string;
22 /**
23 * Redis OSS ACL rule string (e.g. `"on ~keys:* +get"`). See
24 * https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/
25 */
26 rule?: string;
27 };
28
29 export type AclPolicyProps = {
30 /**
31 * ACL policy id (the `{acl_policy}` segment of
32 * `projects/{project}/locations/{location}/aclPolicies/{acl_policy}`).
33 * If omitted, a unique name is generated from the stack, stage, and
34 * logical id. Must match `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$` (1-63
35 * characters). Immutable — changing it replaces the policy.
36 */
37 aclPolicyId?: string;
38 /**
39 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
40 * replaces the policy. `US-CENTRAL1` is accepted and normalized to
41 * `us-central1`.
42 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
43 */
44 location?: string;
45 /**
46 * Redis ACL rules applied to clusters that attach this policy.
47 */
48 rules?: AclRule[];
49 };
50
51 export type AclPolicy = Resource<
52 "GCP.Redis.AclPolicy",
53 AclPolicyProps,
54 {
55 /** Full resource name `projects/{project}/locations/{location}/aclPolicies/{acl_policy}`. */
56 name: string;
57 /** ACL policy id (last path segment). */
58 aclPolicyId: string;
59 /** Project id. */
60 project: string;
61 /** Region id (`us-central1`, …). */
62 location: string;
63 /** ACL rules. */
64 rules: AclRule[];
65 /** Server-reported state (`ACTIVE`, `UPDATING`, `DELETING`, …). */
66 state: string | undefined;
67 /** Server etag for optimistic concurrency. */
68 etag: string | undefined;
69 /** Deprecated drift-resolution version string, if present. */
70 version: string | undefined;
71 },
72 never,
73 Providers
74 >;
75
76 /**
77 * A Memorystore for Redis Cluster ACL policy.
78 *
79 * ACL policies have no labels field, so Alchemy identifies a policy by
80 * its id: a policy found under the generated id is adopted, one found
81 * under an explicit `aclPolicyId` without state is reported as unowned.
82 * `aclPolicyId` and `location` are identity — changing either replaces
83 * the policy. `rules` update in place. Create is synchronous; patch and
84 * delete return long-running operations.
85 *
86 * Attach the policy to a Redis Cluster with the cluster's `aclPolicy`
87 * field. A policy cannot be deleted while it is attached to a cluster.
88 *
89 * ### Creating an ACL Policy
90 * **Example:** Generated name
91 * ```typescript
92 * const policy = yield* GCP.Redis.AclPolicy("AppAcl", {
93 * rules: [{ username: "app", rule: "on ~keys:* +get" }],
94 * });
95 * ```
96 *
97 * **Example:** Explicit id, location, and rules
98 * ```typescript
99 * const policy = yield* GCP.Redis.AclPolicy("AppAcl", {
100 * aclPolicyId: "app-acl",
101 * location: "us-central1",
102 * rules: [
103 * { username: "app", rule: "on ~keys:* +get" },
104 * { username: "readonly", rule: "off ~* -@all" },
105 * ],
106 * });
107 * ```
108 *
109 * ### Updating Rules
110 * Change props on the same logical id; the engine keeps the physical id.
111 *
112 * **Example:** Add a command to an existing user
113 * ```typescript
114 * const policy = yield* GCP.Redis.AclPolicy("AppAcl", {
115 * location: "us-central1",
116 * rules: [{ username: "app", rule: "on ~keys:* +get +set" }],
117 * });
118 * ```
119 *
120 * @resource
121 * @category Redis
122 */
123 export const AclPolicy = Resource<AclPolicy>("GCP.Redis.AclPolicy");
124
125 export class AclPolicyNotResolved extends Data.TaggedError("GCP.Redis.AclPolicyNotResolved")<{
126 resourceName: string;
127 }> {}
128
129 export class AclPolicyNotReady extends Data.TaggedError("GCP.Redis.AclPolicyNotReady")<{
130 resourceName: string;
131 state: string;
132 }> {}
133
134 export class AclPolicyStillExists extends Data.TaggedError("GCP.Redis.AclPolicyStillExists")<{
135 resourceName: string;
136 }> {}
137
138 const lastSegment = (value: string) => {
139 const trimmed = value.replace(/\/+$/, "");
140 const parts = trimmed.split("/");
141 return parts[parts.length - 1] || trimmed;
142 };
143
144 const normalizeLocation = (location: string | undefined, fallback: string) =>
145 lastSegment(location ?? fallback).toLowerCase();
146
147 const rfc1035 = (name: string): string => {
148 let next = name
149 .toLowerCase()
150 .replace(/[^a-z0-9-]/g, "-")
151 .replace(/-+/g, "-")
152 .replace(/^-+|-+$/g, "");
153 if (!/^[a-z]/.test(next)) next = `a${next}`;
154 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
155 if (next.length === 0) return "aclpolicy";
156 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
157 return next.slice(0, MAX_NAME_LENGTH);
158 };
159
160 const resourceName = (project: string, location: string, aclPolicyId: string) =>
161 `projects/${project}/locations/${location}/aclPolicies/${aclPolicyId}`;
162
163 const parseName = (name: string, fallbackLocation: string) => {
164 const parts = name.split("/").filter((part) => part.length > 0);
165 const policiesAt = parts.lastIndexOf("aclPolicies");
166 const locationsAt = parts.lastIndexOf("locations");
167 const projectsAt = parts.lastIndexOf("projects");
168 return {
169 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
170 location:
171 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
172 aclPolicyId:
173 policiesAt >= 0 && parts[policiesAt + 1] ? parts[policiesAt + 1]! : lastSegment(name),
174 };
175 };
176
177 const toId = (id: string, aclPolicyId: string | undefined, existing?: string) =>
178 Effect.gen(function* () {
179 return (
180 aclPolicyId ??
181 existing ??
182 rfc1035(
183 yield* createPhysicalName({
184 id,
185 maxLength: MAX_NAME_LENGTH,
186 lowercase: true,
187 }),
188 )
189 );
190 });
191
192 const ruleOf = (rule: redis.AclRule | AclRule): AclRule => ({
193 username: rule.username,
194 rule: rule.rule,
195 });
196
197 const userRulesOf = (rules: readonly (redis.AclRule | AclRule)[] | undefined): AclRule[] =>
198 (rules ?? []).map(ruleOf);
199
200 const rulesKey = (rules: readonly AclRule[]) =>
201 JSON.stringify(
202 [...rules]
203 .map((rule) => ({
204 username: rule.username ?? "",
205 rule: rule.rule ?? "",
206 }))
207 .sort(
208 (left, right) =>
209 left.username.localeCompare(right.username) || left.rule.localeCompare(right.rule),
210 ),
211 );
212
213 const desiredRules = (news: AclPolicyProps): redis.AclRule[] => userRulesOf(news.rules);
214
215 const toAttrs = (policy: redis.AclPolicy, project: string, region: string) => {
216 const name = policy.name ?? "";
217 const parsed = parseName(name, region);
218 return {
219 name,
220 aclPolicyId: parsed.aclPolicyId,
221 project: parsed.project || project,
222 location: parsed.location,
223 rules: userRulesOf(policy.rules),
224 state: policy.state,
225 etag: policy.etag,
226 version: policy.version,
227 };
228 };
229
230 const isPlaceholder = (policy: redis.AclPolicy) => {
231 const name = policy.name ?? "";
232 return name.endsWith("/aclPolicies/-") || name.endsWith("/aclPolicies/");
233 };
234
235 const getByName = (name: string) =>
236 redis
237 .getProjectsLocationsAclPolicies({ name })
238 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
239
240 /** Wait for an operation through the shared GCP waiter. */
241 const waitForOperation = (operation: redis.Operation, options?: { notFoundOk?: boolean }) =>
242 waitForGcpOperation(
243 operation,
244 (name) =>
245 redis
246 .getProjectsLocationsOperations({ name })
247 .pipe(
248 Effect.catchTag("NotFound", (error) =>
249 options?.notFoundOk === true
250 ? Effect.succeed<redis.Operation>({ name, done: true })
251 : Effect.fail(error),
252 ),
253 ),
254 { budget: "10 minutes" },
255 ).pipe(
256 // ALREADY_EXISTS (6): a concurrent create won the race. NOT_FOUND (5)
257 // is success for a delete.
258 Effect.catchIf(
259 (error) =>
260 error._tag === "GCP.OperationFailed" &&
261 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
262 () => Effect.void,
263 ),
264 );
265
266 const waitUntilExists = (name: string) =>
267 getByName(name).pipe(
268 Effect.flatMap((policy) =>
269 policy
270 ? Effect.succeed(policy)
271 : Effect.fail(new AclPolicyNotResolved({ resourceName: name })),
272 ),
273 Effect.retry({
274 while: (error) => error._tag === "GCP.Redis.AclPolicyNotResolved",
275 times: 8,
276 schedule: Schedule.spaced("1 second"),
277 }),
278 );
279
280 const waitUntilActive = (name: string) =>
281 getByName(name).pipe(
282 Effect.filterOrFail(
283 (policy): policy is redis.AclPolicy => policy !== undefined,
284 () => new AclPolicyNotResolved({ resourceName: name }),
285 ),
286 Effect.filterOrFail(
287 (policy) => {
288 const state = policy.state ?? "ACTIVE";
289 return state === "ACTIVE" || state === "STATE_UNSPECIFIED";
290 },
291 (policy) =>
292 new AclPolicyNotReady({
293 resourceName: name,
294 state: policy.state ?? "STATE_UNSPECIFIED",
295 }),
296 ),
297 Effect.retry({
298 while: (error) =>
299 error._tag === "GCP.Redis.AclPolicyNotReady" ||
300 error._tag === "GCP.Redis.AclPolicyNotResolved",
301 times: 10,
302 schedule: Schedule.spaced("3 seconds"),
303 }),
304 );
305
306 const waitUntilGone = (name: string) =>
307 getByName(name).pipe(
308 Effect.flatMap((policy) =>
309 policy === undefined
310 ? Effect.void
311 : Effect.fail(new AclPolicyStillExists({ resourceName: name })),
312 ),
313 Effect.retry({
314 while: (error) => error._tag === "GCP.Redis.AclPolicyStillExists",
315 times: 10,
316 schedule: Schedule.spaced("3 seconds"),
317 }),
318 );
319
320 export const AclPolicyProvider = () =>
321 Provider.succeed(AclPolicy, {
322 stables: ["name", "aclPolicyId", "project", "location"],
323
324 diff: Effect.fn(function* ({ news, olds, output }) {
325 if (!isResolved(news)) return undefined;
326 const env = yield* GcpEnvironment.current;
327
328 const previousId = olds?.aclPolicyId ?? output?.aclPolicyId;
329 const nextId = news.aclPolicyId ?? previousId;
330 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
331 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
332 const replace =
333 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
334 previousLocation !== nextLocation;
335 if (!replace) return undefined;
336 return { action: "replace" as const, deleteFirst: false };
337 }),
338
339 read: Effect.fn(function* ({ id, olds, output }) {
340 const env = yield* GcpEnvironment.current;
341 const aclPolicyId = yield* toId(id, olds?.aclPolicyId, output?.aclPolicyId);
342 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
343 const name = output?.name ?? resourceName(env.project, location, aclPolicyId);
344 const existing = yield* getByName(name);
345 if (existing === undefined) return undefined;
346 const attrs = toAttrs(existing, env.project, env.region);
347 // No labels: state or the generated id proves ownership.
348 return output !== undefined || olds?.aclPolicyId === undefined ? attrs : Unowned(attrs);
349 }),
350
351 reconcile: Effect.fn(function* ({ id, news, output }) {
352 const env = yield* GcpEnvironment.current;
353 const aclPolicyId = yield* toId(id, news.aclPolicyId, output?.aclPolicyId);
354 const location = normalizeLocation(news.location ?? output?.location, env.region);
355 const name = resourceName(env.project, location, aclPolicyId);
356 const bodyRules = desiredRules(news);
357
358 let current = yield* getByName(output?.name ?? name);
359 if (current !== undefined && (current.state ?? "") === "DELETING") {
360 yield* waitUntilGone(name);
361 current = undefined;
362 }
363
364 if (current === undefined) {
365 const created = yield* redis
366 .createProjectsLocationsAclPolicies({
367 parent: `projects/${env.project}/locations/${location}`,
368 aclPolicyId,
369 body: { rules: bodyRules },
370 })
371 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
372 current =
373 created && created.name && !isPlaceholder(created)
374 ? created
375 : yield* waitUntilExists(name);
376 }
377
378 if (current === undefined) {
379 return yield* new AclPolicyNotResolved({ resourceName: name });
380 }
381
382 const state = current.state ?? "ACTIVE";
383 if (state === "UPDATING" || state === "DELETING") {
384 current = yield* waitUntilActive(name);
385 }
386
387 const rulesChanged =
388 rulesKey(userRulesOf(current.rules)) !== rulesKey(userRulesOf(news.rules));
389
390 if (rulesChanged) {
391 const patched = yield* redis
392 .patchProjectsLocationsAclPolicies({
393 name,
394 updateMask: "rules",
395 body: { name, rules: bodyRules },
396 })
397 .pipe(
398 Effect.retry({
399 while: (error) => error._tag === "Conflict",
400 times: 8,
401 schedule: Schedule.spaced("2 seconds"),
402 }),
403 );
404 yield* waitForOperation(patched);
405 current = yield* waitUntilActive(name);
406 }
407
408 return toAttrs(current, env.project, env.region);
409 }),
410
411 delete: Effect.fn(function* ({ output }) {
412 const operation = yield* redis
413 .deleteProjectsLocationsAclPolicies({
414 name: output.name,
415 })
416 .pipe(
417 Effect.catchTag("NotFound", () => Effect.undefined),
418 Effect.retry({
419 while: (error) => error._tag === "Conflict",
420 times: 8,
421 schedule: Schedule.spaced("2 seconds"),
422 }),
423 );
424 if (operation !== undefined) {
425 yield* waitForOperation(operation, { notFoundOk: true });
426 }
427 yield* waitUntilGone(output.name);
428 }),
429 });