@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 279 lines 9.29 KB
Raw
1 import * as composer from "@distilled.cloud/gcp/composer_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 * as Schedule from "effect/Schedule";
9 import type { Providers } from "../Providers.ts";
10 import {
11 dataKey,
12 environmentParent,
13 lastSegment,
14 mapOf,
15 parseWorkloadName,
16 toPhysicalId,
17 } from "./internal.ts";
18
19 export type EnvironmentsUserWorkloadsSecretProps = {
20 /**
21 * Parent environment resource name
22 * (`projects/{project}/locations/{location}/environments/{environment}`).
23 * Immutable — changing it replaces the Secret.
24 */
25 environmentName: string;
26 /**
27 * Secret id (the last path segment). If omitted, a unique RFC1035 name
28 * is generated from the stack, stage, and logical id. Must start with a
29 * lowercase letter, be 1-63 characters, and match
30 * `[a-z]([-a-z0-9]*[a-z0-9])?`. Immutable — changing it replaces the
31 * Secret.
32 */
33 secretId?: string;
34 /**
35 * Kubernetes Secret data as key-value pairs. Values must be
36 * base64-encoded strings. Stored exactly as given: Secrets have no
37 * labels, so Alchemy tracks them by name.
38 *
39 * `secrets.get` clears data values in the response; keys remain.
40 */
41 data?: Record<string, string>;
42 };
43
44 export type EnvironmentsUserWorkloadsSecret = Resource<
45 "GCP.Composer.EnvironmentsUserWorkloadsSecret",
46 EnvironmentsUserWorkloadsSecretProps,
47 {
48 /** Full resource name `{environment}/userWorkloadsSecrets/{secretId}`. */
49 name: string;
50 /** Secret id (last path segment). */
51 secretId: string;
52 /** Parent environment resource name. */
53 environmentName: string;
54 /** Project id. */
55 project: string;
56 /** Region id (`us-central1`, …). */
57 location: string;
58 /** Parent environment id. */
59 environmentId: string;
60 /**
61 * Secret data. `secrets.get` clears
62 * values, so this may contain empty strings after a refresh.
63 */
64 data: Record<string, string>;
65 },
66 never,
67 Providers
68 >;
69
70 /**
71 * A user workloads Secret for Airflow tasks that run with the Kubernetes
72 * executor or KubernetesPodOperator.
73 *
74 * Supported on Cloud Composer 3 (`composer-3-airflow-2` and newer).
75 * Secrets have no labels field, so Alchemy tracks them by name and
76 * never adds keys to `data`. `environmentName` and `secretId` are
77 * identity — changing either replaces the Secret. Data values must be
78 * base64-encoded.
79 *
80 * ### Creating a User Workloads Secret
81 * **Example:** Generated name
82 * ```typescript
83 * const airflow = yield* GCP.Composer.Environment("Airflow", {
84 * config: {
85 * environmentSize: "ENVIRONMENT_SIZE_SMALL",
86 * nodeConfig: {
87 * serviceAccount: "composer-env@my-project.iam.gserviceaccount.com",
88 * },
89 * softwareConfig: { imageVersion: "composer-3-airflow-2" },
90 * },
91 * });
92 * const secret = yield* GCP.Composer.EnvironmentsUserWorkloadsSecret(
93 * "TaskSecret",
94 * {
95 * environmentName: airflow.name,
96 * data: { password: btoa("s3cret") },
97 * },
98 * );
99 * ```
100 *
101 * **Example:** Explicit id
102 * ```typescript
103 * const secret = yield* GCP.Composer.EnvironmentsUserWorkloadsSecret(
104 * "TaskSecret",
105 * {
106 * environmentName: airflow.name,
107 * secretId: "task-secret",
108 * data: { token: btoa("abc123") },
109 * },
110 * );
111 * ```
112 *
113 * ### Updating data
114 * **Example:** Rotate a value
115 * ```typescript
116 * const secret = yield* GCP.Composer.EnvironmentsUserWorkloadsSecret(
117 * "TaskSecret",
118 * {
119 * environmentName: airflow.name,
120 * secretId: "task-secret",
121 * data: { token: btoa("rotated") },
122 * },
123 * );
124 * ```
125 *
126 * @resource
127 * @category Composer
128 */
129 export const EnvironmentsUserWorkloadsSecret = Resource<EnvironmentsUserWorkloadsSecret>(
130 "GCP.Composer.EnvironmentsUserWorkloadsSecret",
131 );
132
133 export class EnvironmentsUserWorkloadsSecretNotResolved extends Data.TaggedError(
134 "GCP.Composer.EnvironmentsUserWorkloadsSecretNotResolved",
135 )<{
136 resourceName: string;
137 }> {}
138
139 export class EnvironmentsUserWorkloadsSecretStillExists extends Data.TaggedError(
140 "GCP.Composer.EnvironmentsUserWorkloadsSecretStillExists",
141 )<{
142 resourceName: string;
143 }> {}
144
145 const resourceName = (environmentName: string, secretId: string) =>
146 `${environmentParent(environmentName)}/userWorkloadsSecrets/${secretId}`;
147
148 const toAttrs = (secret: composer.UserWorkloadsSecret, environmentName: string) => {
149 const name = secret.name ?? resourceName(environmentName, "");
150 const parsed = parseWorkloadName(name);
151 const parent = environmentParent(environmentName || name);
152 return {
153 name,
154 secretId: parsed.secretId ?? lastSegment(name),
155 environmentName: parent,
156 project: parsed.project,
157 location: parsed.location,
158 environmentId: parsed.environmentId,
159 data: mapOf(secret.data),
160 };
161 };
162
163 const getByName = (name: string) =>
164 composer
165 .getProjectsLocationsEnvironmentsUserWorkloadsSecrets({ name })
166 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
167
168 const waitUntilGone = (name: string) =>
169 getByName(name).pipe(
170 Effect.flatMap((current) =>
171 current === undefined
172 ? Effect.void
173 : Effect.fail(new EnvironmentsUserWorkloadsSecretStillExists({ resourceName: name })),
174 ),
175 Effect.retry({
176 while: (error) => error._tag === "GCP.Composer.EnvironmentsUserWorkloadsSecretStillExists",
177 times: 8,
178 schedule: Schedule.spaced("2 seconds"),
179 }),
180 );
181
182 const keysOf = (map: Record<string, string>) => Object.keys(map).sort().join("\0");
183
184 const valuesCleared = (map: Record<string, string>) =>
185 Object.values(map).every((value) => value.length === 0);
186
187 export const EnvironmentsUserWorkloadsSecretProvider = () =>
188 Provider.succeed(EnvironmentsUserWorkloadsSecret, {
189 stables: ["name", "secretId", "environmentName", "project", "location", "environmentId"],
190
191 diff: Effect.fn(function* ({ news, olds, output }) {
192 if (!isResolved(news)) return undefined;
193 const previousId = olds?.secretId ?? output?.secretId;
194 const idChanged =
195 previousId !== undefined && news.secretId !== undefined && news.secretId !== previousId;
196 const previousParent = olds?.environmentName ?? output?.environmentName;
197 const parentChanged =
198 previousParent !== undefined &&
199 environmentParent(news.environmentName) !== environmentParent(previousParent);
200 if (!idChanged && !parentChanged) return undefined;
201 return { action: "replace" as const, deleteFirst: false };
202 }),
203
204 read: Effect.fn(function* ({ id, olds, output }) {
205 const environmentName = olds?.environmentName ?? output?.environmentName;
206 if (environmentName === undefined) return undefined;
207 const secretId = yield* toPhysicalId(id, olds?.secretId, output?.secretId);
208 const name = output?.name ?? resourceName(environmentName, secretId);
209 const existing = yield* getByName(name);
210 if (existing === undefined) return undefined;
211 const attrs = toAttrs(existing, environmentName);
212 // No labels: a generated id embeds stack/stage/id, and a row we
213 // created is in state. Only an explicit id found without state is
214 // ambiguous.
215 return output === undefined && olds?.secretId !== undefined ? Unowned(attrs) : attrs;
216 }),
217
218 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
219 const secretId = yield* toPhysicalId(id, news.secretId, output?.secretId);
220 const parent = environmentParent(news.environmentName);
221 const name = resourceName(parent, secretId);
222 const desiredData = mapOf(news.data);
223
224 let current = yield* getByName(output?.name ?? name);
225
226 if (current === undefined) {
227 const created = yield* composer
228 .createProjectsLocationsEnvironmentsUserWorkloadsSecrets({
229 parent,
230 body: {
231 name,
232 data: desiredData,
233 },
234 })
235 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
236 current = created ?? undefined;
237 }
238
239 if (current === undefined) {
240 return yield* new EnvironmentsUserWorkloadsSecretNotResolved({ resourceName: name });
241 }
242
243 const observed = mapOf(current.data);
244 const observedCleared = valuesCleared(observed);
245 const keysChanged = keysOf(observed) !== keysOf(desiredData);
246 const desiredUserChanged = dataKey(news.data) !== dataKey(olds?.data);
247 const shouldSync =
248 (!observedCleared && dataKey(observed) !== dataKey(desiredData)) ||
249 (observedCleared && (keysChanged || desiredUserChanged));
250
251 if (shouldSync) {
252 current = yield* composer.updateProjectsLocationsEnvironmentsUserWorkloadsSecrets({
253 name: current.name ?? name,
254 body: {
255 name: current.name ?? name,
256 data: desiredData,
257 },
258 });
259 }
260
261 return toAttrs(current, parent);
262 }),
263
264 delete: Effect.fn(function* ({ output }) {
265 yield* composer
266 .deleteProjectsLocationsEnvironmentsUserWorkloadsSecrets({
267 name: output.name,
268 })
269 .pipe(
270 Effect.catchTag("NotFound", () => Effect.void),
271 Effect.retry({
272 while: (error) => error._tag === "Conflict",
273 times: 8,
274 schedule: Schedule.spaced("2 seconds"),
275 }),
276 );
277 yield* waitUntilGone(output.name);
278 }),
279 });