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