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

main
ts 310 lines 9.5 KB
Raw
1 import * as kafka from "@distilled.cloud/gcp/managedkafka_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 collectPages,
12 expandParent,
13 fingerprint,
14 getAcl,
15 listAlchemyClusters,
16 normalizeLocation,
17 parseName,
18 replaceOnIdentity,
19 retryTransient,
20 toPhysicalId,
21 } from "./internal.ts";
22
23 export type AclEntry = {
24 /**
25 * Operation (`ALL`, `READ`, `WRITE`, `CREATE`, `DELETE`, `ALTER`,
26 * `DESCRIBE`, `CLUSTER_ACTION`, `DESCRIBE_CONFIGS`, `ALTER_CONFIGS`,
27 * `IDEMPOTENT_WRITE`).
28 */
29 operation?: string;
30 /**
31 * Host. Must be `*` for Managed Service for Apache Kafka.
32 * @default "*"
33 */
34 host?: string;
35 /**
36 * Permission type (`ALLOW`, `DENY`).
37 */
38 permissionType?: string;
39 /**
40 * Principal (`User:sa@project.iam.gserviceaccount.com` or `User:*`).
41 */
42 principal?: string;
43 };
44
45 export type ClustersAclProps = {
46 /**
47 * Parent cluster. Full name
48 * `projects/{project}/locations/{location}/clusters/{cluster}` or the
49 * cluster id (combined with `location`). Immutable — changing it
50 * replaces the ACL.
51 */
52 cluster: string;
53 /**
54 * Region used when `cluster` is a bare id.
55 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
56 */
57 location?: string;
58 /**
59 * ACL id. Defines the Resource Pattern:
60 * `cluster`, `topic/{name}`, `consumerGroup/{name}`,
61 * `transactionalId/{name}`, `topicPrefixed/{name}`, `allTopics`,
62 * `allConsumerGroups`, `allTransactionalIds`. If omitted, a topic
63 * pattern is generated from the logical id. Immutable — changing it
64 * replaces the ACL.
65 */
66 aclId?: string;
67 /**
68 * ACL entries for the resource pattern. Maximum 100.
69 */
70 aclEntries: AclEntry[];
71 };
72
73 export type ClustersAcl = Resource<
74 "GCP.ManagedKafka.ClustersAcl",
75 ClustersAclProps,
76 {
77 /** Full resource name `.../clusters/{cluster}/acls/{acl_id}`. */
78 name: string;
79 /** ACL id (resource pattern). */
80 aclId: string;
81 /** Parent cluster resource name. */
82 cluster: string;
83 /** Project id. */
84 project: string;
85 /** Location id. */
86 location: string;
87 /** ACL entries currently applied. */
88 aclEntries: AclEntry[];
89 /** Pattern type (`LITERAL`, `PREFIXED`). */
90 patternType: string | undefined;
91 /** Resource name derived from the ACL id. */
92 resourceName: string | undefined;
93 /** Resource type (`CLUSTER`, `TOPIC`, `GROUP`, `TRANSACTIONAL_ID`). */
94 resourceType: string | undefined;
95 /** Etag for concurrency control. */
96 etag: string | undefined;
97 },
98 never,
99 Providers
100 >;
101
102 /**
103 * An ACL for a Kafka resource pattern on a Managed Kafka cluster.
104 *
105 * The ACL id encodes the resource pattern and is immutable. Entries
106 * update in place.
107 *
108 * ### Creating an ACL
109 * **Example:** Allow all users to describe a topic
110 * ```typescript
111 * const acl = yield* GCP.ManagedKafka.ClustersAcl("OrdersAcl", {
112 * cluster: cluster.name,
113 * aclId: "topic/orders",
114 * aclEntries: [
115 * {
116 * principal: "User:*",
117 * operation: "DESCRIBE",
118 * permissionType: "ALLOW",
119 * host: "*",
120 * },
121 * ],
122 * });
123 * ```
124 *
125 * **Example:** Cluster-wide ACL
126 * ```typescript
127 * const acl = yield* GCP.ManagedKafka.ClustersAcl("ClusterAcl", {
128 * cluster: cluster.name,
129 * aclId: "cluster",
130 * aclEntries: [
131 * {
132 * principal: "User:client@my-project.iam.gserviceaccount.com",
133 * operation: "CLUSTER_ACTION",
134 * permissionType: "ALLOW",
135 * host: "*",
136 * },
137 * ],
138 * });
139 * ```
140 *
141 * @resource
142 * @category ManagedKafka
143 */
144 export const ClustersAcl = Resource<ClustersAcl>("GCP.ManagedKafka.ClustersAcl");
145
146 export class ClustersAclNotResolved extends Data.TaggedError(
147 "GCP.ManagedKafka.ClustersAclNotResolved",
148 )<{
149 resourceName: string;
150 }> {}
151
152 const clusterOf = (cluster: string, project: string, location: string) =>
153 expandParent(cluster, project, location, "clusters");
154
155 const resourceName = (cluster: string, aclId: string) => `${cluster}/acls/${aclId}`;
156
157 const entriesOf = (entries: readonly kafka.AclEntry[] | undefined): AclEntry[] =>
158 (entries ?? []).map((entry) => ({
159 operation: entry.operation,
160 host: entry.host ?? "*",
161 permissionType: entry.permissionType,
162 principal: entry.principal,
163 }));
164
165 const entriesKey = (entries: readonly AclEntry[] | undefined) =>
166 fingerprint(
167 entriesOf(entries).map((entry) => ({
168 operation: (entry.operation ?? "").toUpperCase(),
169 host: entry.host ?? "*",
170 permissionType: (entry.permissionType ?? "").toUpperCase(),
171 principal: entry.principal ?? "",
172 })),
173 );
174
175 const toAttrs = (acl: kafka.Acl, project: string) => {
176 const name = acl.name ?? "";
177 const parsed = parseName(name, "acls");
178 return {
179 name,
180 aclId: parsed.id,
181 cluster: parsed.parent,
182 project: parsed.project || project,
183 location: parsed.location,
184 aclEntries: entriesOf(acl.aclEntries),
185 patternType: acl.patternType,
186 resourceName: acl.resourceName,
187 resourceType: acl.resourceType,
188 etag: acl.etag,
189 };
190 };
191
192 const toAclId = (id: string, explicit: string | undefined, existing: string | undefined) =>
193 Effect.gen(function* () {
194 if (explicit !== undefined) return explicit;
195 if (existing !== undefined) return existing;
196 const topicId = yield* toPhysicalId(id, undefined, undefined, "topic");
197 return `topic/${topicId}`;
198 });
199
200 export const ClustersAclProvider = () =>
201 Provider.succeed(ClustersAcl, {
202 stables: [
203 "name",
204 "aclId",
205 "cluster",
206 "project",
207 "location",
208 "patternType",
209 "resourceName",
210 "resourceType",
211 ],
212
213 diff: Effect.fn(function* ({ news, olds, output }) {
214 if (!isResolved(news)) return undefined;
215 const env = yield* GcpEnvironment.current;
216 const location = normalizeLocation(news.location ?? output?.location, env.region);
217 return replaceOnIdentity({
218 previousId: olds?.aclId ?? output?.aclId,
219 nextId: news.aclId ?? olds?.aclId ?? output?.aclId,
220 previousParent: olds?.cluster ?? output?.cluster,
221 nextParent: clusterOf(news.cluster, env.project, location),
222 });
223 }),
224
225 read: Effect.fn(function* ({ id, olds, output }) {
226 const env = yield* GcpEnvironment.current;
227 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
228 const aclId = yield* toAclId(id, olds?.aclId, output?.aclId);
229 const cluster =
230 olds?.cluster !== undefined
231 ? clusterOf(olds.cluster, env.project, location)
232 : (output?.cluster ?? "");
233 const name = output?.name ?? (cluster.length > 0 ? resourceName(cluster, aclId) : "");
234 const existing = yield* getAcl(name);
235 if (existing === undefined) return undefined;
236 const attrs = toAttrs(existing, env.project);
237 return output !== undefined || olds !== undefined ? attrs : Unowned(attrs);
238 }),
239
240 list: () =>
241 Effect.gen(function* () {
242 const env = yield* GcpEnvironment.current;
243 const clusters = yield* listAlchemyClusters(env.project, env.region);
244 const acls = yield* Effect.forEach(
245 clusters.filter((cluster) => (cluster.name ?? "").length > 0),
246 (cluster: kafka.Cluster) =>
247 collectPages(
248 kafka.listProjectsLocationsClustersAcls.pages({
249 parent: cluster.name!,
250 pageSize: 1000,
251 }),
252 (page) => page.acls,
253 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as kafka.Acl[]))),
254 { concurrency: 4 },
255 );
256 return acls.flat().map((acl) => toAttrs(acl, env.project));
257 }),
258
259 reconcile: Effect.fn(function* ({ id, news, output }) {
260 const env = yield* GcpEnvironment.current;
261 const location = normalizeLocation(news.location ?? output?.location, env.region);
262 const cluster = clusterOf(news.cluster, env.project, location);
263 const aclId = yield* toAclId(id, news.aclId, output?.aclId);
264 const name = output?.name ?? resourceName(cluster, aclId);
265 const aclEntries = news.aclEntries.map((entry) => ({
266 operation: entry.operation,
267 host: entry.host ?? "*",
268 permissionType: entry.permissionType,
269 principal: entry.principal,
270 }));
271
272 let current = yield* getAcl(name);
273
274 if (current === undefined) {
275 const created = yield* retryTransient(
276 kafka
277 .createProjectsLocationsClustersAcls({
278 parent: cluster,
279 aclId,
280 body: { aclEntries },
281 })
282 .pipe(Effect.catchTag("Conflict", () => getAcl(name))),
283 );
284 current = created ?? undefined;
285 }
286
287 if (current === undefined) {
288 return yield* new ClustersAclNotResolved({ resourceName: name });
289 }
290
291 if (entriesKey(current.aclEntries) !== entriesKey(aclEntries)) {
292 current = yield* kafka.patchProjectsLocationsClustersAcls({
293 name,
294 updateMask: "acl_entries",
295 body: {
296 aclEntries,
297 etag: current.etag,
298 },
299 });
300 }
301
302 return toAttrs(current, env.project);
303 }),
304
305 delete: Effect.fn(function* ({ output }) {
306 yield* kafka
307 .deleteProjectsLocationsClustersAcls({ name: output.name })
308 .pipe(Effect.catchTag(["NotFound", "AclClusterNotFound"], () => Effect.void));
309 }),
310 });