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

main
ts 261 lines 9.14 KB
Raw
1 import * as dataplex from "@distilled.cloud/gcp/dataplex_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 Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 DataplexNotResolved,
12 normalizeLocation,
13 parseName,
14 replaceOnIdentity,
15 retryQuota,
16 waitForOperation,
17 waitUntilExists,
18 waitUntilGone,
19 } from "./internal.ts";
20
21 const DEFAULT_ENCRYPTION_CONFIG_ID = "default";
22
23 export type EncryptionConfigFailureDetails =
24 dataplex.GoogleCloudDataplexV1EncryptionConfigFailureDetails;
25
26 export type EncryptionConfigProps = {
27 /**
28 * Organization id (the `{organization}` segment of
29 * `organizations/{organization}/locations/{location}/encryptionConfigs/{encryptionConfig}`).
30 * Immutable — changing it replaces the config.
31 */
32 organizationId: string;
33 /**
34 * Region (`us-central1`, …). Global is not supported. Immutable —
35 * changing it replaces the config.
36 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
37 */
38 location?: string;
39 /**
40 * EncryptionConfig id. Currently only `"default"` is supported.
41 * Immutable — changing it replaces the config.
42 * @default "default"
43 */
44 encryptionConfigId?: string;
45 /**
46 * Cloud KMS key for CMEK. Omit to use Google-managed encryption.
47 */
48 key?: string;
49 /**
50 * Opt the metastore into CMEK.
51 * @default false
52 */
53 enableMetastoreEncryption?: boolean;
54 };
55
56 export type EncryptionConfig = Resource<
57 "GCP.Dataplex.EncryptionConfig",
58 EncryptionConfigProps,
59 {
60 /** Full resource name. */
61 name: string;
62 /** EncryptionConfig id (last path segment). */
63 encryptionConfigId: string;
64 /** Organization id. */
65 organizationId: string;
66 /** Location id. */
67 location: string;
68 /** CMEK key, if any. */
69 key: string | undefined;
70 /** Whether metastore CMEK is enabled. */
71 enableMetastoreEncryption: boolean;
72 /** Encryption state. */
73 encryptionState: string | undefined;
74 /** Failure details, if any. */
75 failureDetails: EncryptionConfigFailureDetails | undefined;
76 /** Server etag. */
77 etag: string | undefined;
78 /** RFC3339 creation timestamp. */
79 createTime: string | undefined;
80 /** RFC3339 last-update timestamp. */
81 updateTime: string | undefined;
82 },
83 never,
84 Providers
85 >;
86
87 /**
88 * A Dataplex EncryptionConfig that opts an organization location into
89 * customer-managed encryption keys (CMEK).
90 *
91 * EncryptionConfigs have no labels field. Organization, location, and id
92 * are immutable (`default` is the only supported id). Key and metastore
93 * encryption update in place. `list` returns an empty set because
94 * ownership cannot be stamped on this org singleton.
95 *
96 * ### Creating an EncryptionConfig
97 * **Example:** Google-managed encryption at us-central1
98 * ```typescript
99 * const config = yield* GCP.Dataplex.EncryptionConfig("Default", {
100 * organizationId: "1234567890",
101 * location: "us-central1",
102 * });
103 * ```
104 *
105 * @resource
106 * @category Dataplex
107 */
108 export const EncryptionConfig = Resource<EncryptionConfig>("GCP.Dataplex.EncryptionConfig");
109
110 const orgParent = (organizationId: string, location: string) =>
111 `organizations/${organizationId}/locations/${location}`;
112
113 const resourceName = (organizationId: string, location: string, encryptionConfigId: string) =>
114 `${orgParent(organizationId, location)}/encryptionConfigs/${encryptionConfigId}`;
115
116 const toId = (encryptionConfigId: string | undefined, existing?: string) =>
117 encryptionConfigId ?? existing ?? DEFAULT_ENCRYPTION_CONFIG_ID;
118
119 const toAttrs = (
120 config: dataplex.GoogleCloudDataplexV1EncryptionConfig,
121 organizationId: string,
122 ) => {
123 const name = config.name ?? "";
124 const parsed = parseName(name, "encryptionConfigs");
125 return {
126 name,
127 encryptionConfigId: parsed.id || DEFAULT_ENCRYPTION_CONFIG_ID,
128 organizationId: parsed.organization || organizationId,
129 location: parsed.location,
130 key: config.key,
131 enableMetastoreEncryption: config.enableMetastoreEncryption === true,
132 encryptionState: config.encryptionState,
133 failureDetails: config.failureDetails,
134 etag: config.etag,
135 createTime: config.createTime,
136 updateTime: config.updateTime,
137 };
138 };
139
140 const getByName = (name: string) =>
141 name.length === 0
142 ? Effect.undefined
143 : retryQuota(dataplex.getOrganizationsLocationsEncryptionConfigs({ name })).pipe(
144 Effect.catchTag("NotFound", () => Effect.undefined),
145 );
146
147 export const EncryptionConfigProvider = () =>
148 Provider.succeed(EncryptionConfig, {
149 stables: ["name", "encryptionConfigId", "organizationId", "location", "createTime"],
150
151 diff: Effect.fn(function* ({ news, olds, output }) {
152 if (!isResolved(news)) return undefined;
153 const env = yield* GcpEnvironment.current;
154 return replaceOnIdentity({
155 previousId:
156 olds?.encryptionConfigId ?? output?.encryptionConfigId ?? DEFAULT_ENCRYPTION_CONFIG_ID,
157 nextId: toId(
158 news.encryptionConfigId,
159 olds?.encryptionConfigId ?? output?.encryptionConfigId,
160 ),
161 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
162 nextLocation: normalizeLocation(
163 news.location ?? olds?.location ?? output?.location,
164 env.region,
165 ),
166 previousParent: olds?.organizationId ?? output?.organizationId,
167 nextParent: news.organizationId,
168 });
169 }),
170
171 read: Effect.fn(function* ({ olds, output }) {
172 const env = yield* GcpEnvironment.current;
173 const encryptionConfigId = toId(olds?.encryptionConfigId, output?.encryptionConfigId);
174 const organizationId = olds?.organizationId ?? output?.organizationId;
175 if (organizationId === undefined) return undefined;
176 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
177 const name = output?.name ?? resourceName(organizationId, location, encryptionConfigId);
178 const existing = yield* getByName(name);
179 if (existing === undefined) return undefined;
180 const attrs = toAttrs(existing, organizationId);
181 return output !== undefined ? attrs : Unowned(attrs);
182 }),
183
184 list: () => Effect.succeed([]),
185
186 reconcile: Effect.fn(function* ({ news, output }) {
187 const env = yield* GcpEnvironment.current;
188 const encryptionConfigId = toId(news.encryptionConfigId, output?.encryptionConfigId);
189 const location = normalizeLocation(news.location ?? output?.location, env.region);
190 const name = resourceName(news.organizationId, location, encryptionConfigId);
191
192 let current = yield* getByName(output?.name ?? name);
193
194 if (current === undefined) {
195 const created = yield* retryQuota(
196 dataplex.createOrganizationsLocationsEncryptionConfigs({
197 parent: orgParent(news.organizationId, location),
198 encryptionConfigId,
199 body: {
200 key: news.key,
201 enableMetastoreEncryption: news.enableMetastoreEncryption === true ? true : undefined,
202 },
203 }),
204 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
205 if (created !== undefined) {
206 yield* waitForOperation(created);
207 }
208 current = yield* waitUntilExists(getByName(name), name);
209 }
210
211 if (current === undefined) {
212 return yield* new DataplexNotResolved({ resourceName: name });
213 }
214
215 const keyChanged = (current.key ?? "") !== (news.key ?? "");
216 const metastoreChanged =
217 (current.enableMetastoreEncryption === true) !== (news.enableMetastoreEncryption === true);
218
219 if (keyChanged || metastoreChanged) {
220 const operation = yield* dataplex.patchOrganizationsLocationsEncryptionConfigs({
221 name: current.name ?? name,
222 updateMask: [
223 keyChanged ? "key" : undefined,
224 metastoreChanged ? "enableMetastoreEncryption" : undefined,
225 ]
226 .filter((field): field is string => field !== undefined)
227 .join(","),
228 body: {
229 name: current.name ?? name,
230 key: news.key,
231 enableMetastoreEncryption: news.enableMetastoreEncryption === true,
232 etag: current.etag,
233 },
234 });
235 yield* waitForOperation(operation);
236 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
237 }
238
239 return toAttrs(current, news.organizationId);
240 }),
241
242 delete: Effect.fn(function* ({ output }) {
243 const operation = yield* dataplex
244 .deleteOrganizationsLocationsEncryptionConfigs({
245 name: output.name,
246 etag: output.etag,
247 })
248 .pipe(
249 Effect.retry({
250 while: (error) => error._tag === "Conflict",
251 times: 8,
252 schedule: Schedule.spaced("2 seconds"),
253 }),
254 Effect.catchTag("NotFound", () => Effect.undefined),
255 );
256 if (operation !== undefined) {
257 yield* waitForOperation(operation, { notFoundOk: true });
258 }
259 yield* waitUntilGone(getByName(output.name), output.name);
260 }),
261 });