@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 401 lines 14.1 KB
Raw
1 import * as networkservices from "@distilled.cloud/gcp/networkservices_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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DEFAULT_ZONE,
14 MAX_MULTICAST_NAME_LENGTH,
15 changedFields,
16 collectPages,
17 hasAlchemyLabelKeys,
18 linkKey,
19 normalizeLocation,
20 parentOf,
21 parseName,
22 resourceName,
23 rfc1035,
24 sameJson,
25 toNamedResource,
26 toPhysicalId,
27 userLabels,
28 waitForOperation,
29 waitUntilGone,
30 waitUntilPresent,
31 } from "./internal.ts";
32
33 const COLLECTION = "multicastGroupConsumerActivations";
34
35 export type MulticastLogConfig = {
36 /**
37 * Export multicast group-consumer activity to Cloud Logging.
38 * @default false
39 */
40 enabled?: boolean;
41 };
42
43 export type MulticastGroupConsumerActivationProps = {
44 /**
45 * Activation id (the `{multicastGroupConsumerActivation}` segment of
46 * `projects/{project}/locations/{location}/multicastGroupConsumerActivations/{multicastGroupConsumerActivation}`).
47 * If omitted, a unique name is generated from the stack, stage, and
48 * logical id. Must be at most 48 characters. Immutable — changing it
49 * replaces the activation.
50 */
51 multicastGroupConsumerActivationId?: string;
52 /**
53 * Zone of the activation (`us-central1-a`, …). Immutable — changing
54 * it replaces the activation. `US-CENTRAL1-A` is accepted and
55 * normalized to `us-central1-a`.
56 * @default "us-central1-a"
57 */
58 location?: string;
59 /**
60 * Multicast consumer association in the same zone
61 * (`projects/{project}/locations/{location}/multicastConsumerAssociations/{association}`).
62 * Immutable — changing it replaces the activation.
63 */
64 multicastConsumerAssociation: string;
65 /**
66 * Multicast group range activation in the same zone
67 * (`projects/{project}/locations/{location}/multicastGroupRangeActivations/{activation}`).
68 * Immutable — changing it replaces the activation.
69 */
70 multicastGroupRangeActivation: string;
71 /**
72 * Deprecated multicast group resource name. Prefer
73 * `multicastGroupRangeActivation`.
74 */
75 multicastGroup?: string;
76 /**
77 * Human-readable description.
78 */
79 description?: string;
80 /**
81 * Logging options for this activation.
82 */
83 logConfig?: MulticastLogConfig;
84 /**
85 * User labels. Alchemy ownership labels are merged in automatically.
86 */
87 labels?: Record<string, string>;
88 };
89
90 export type MulticastGroupConsumerActivation = Resource<
91 "GCP.NetworkServices.MulticastGroupConsumerActivation",
92 MulticastGroupConsumerActivationProps,
93 {
94 /** Full resource name `projects/{project}/locations/{location}/multicastGroupConsumerActivations/{multicastGroupConsumerActivation}`. */
95 name: string;
96 /** Activation id (last path segment). */
97 multicastGroupConsumerActivationId: string;
98 /** Project id. */
99 project: string;
100 /** Zone id (`us-central1-a`, …). */
101 location: string;
102 /** Attached multicast consumer association. */
103 multicastConsumerAssociation: string | undefined;
104 /** Attached multicast group range activation. */
105 multicastGroupRangeActivation: string | undefined;
106 /** Deprecated multicast group name, if set. */
107 multicastGroup: string | undefined;
108 /** User-provided description. */
109 description: string | undefined;
110 /** Logging configuration. */
111 logConfig: MulticastLogConfig | undefined;
112 /** Deprecated resource-state enum. */
113 resourceState: string | undefined;
114 /** Nested multicast resource state. */
115 state: string | undefined;
116 /** Google-generated UUID. */
117 uniqueId: string | undefined;
118 /** User labels (Alchemy ownership labels stripped). */
119 labels: Record<string, string>;
120 /** RFC3339 creation timestamp. */
121 createTime: string | undefined;
122 /** RFC3339 last-update timestamp. */
123 updateTime: string | undefined;
124 },
125 never,
126 Providers
127 >;
128
129 /**
130 * A multicast group consumer activation lets VMs in an associated
131 * consumer VPC join a multicast group range in the same zone.
132 *
133 * Changing `multicastGroupConsumerActivationId`, `location`,
134 * `multicastConsumerAssociation`, or `multicastGroupRangeActivation`
135 * replaces the activation. Description, labels, and log config update
136 * in place.
137 *
138 * ### Creating a MulticastGroupConsumerActivation
139 * **Example:** Activate a group range for a consumer VPC
140 * ```typescript
141 * const activation = yield* GCP.NetworkServices.MulticastGroupConsumerActivation(
142 * "Join",
143 * {
144 * location: association.location,
145 * multicastConsumerAssociation: association.name,
146 * multicastGroupRangeActivation: rangeActivation.name,
147 * logConfig: { enabled: true },
148 * labels: { env: "prod" },
149 * },
150 * );
151 * ```
152 *
153 * @resource
154 * @category NetworkServices
155 */
156 export const MulticastGroupConsumerActivation = Resource<MulticastGroupConsumerActivation>(
157 "GCP.NetworkServices.MulticastGroupConsumerActivation",
158 );
159
160 const toAssociation = (project: string, location: string, value: string | undefined) =>
161 value ? toNamedResource(project, location, "multicastConsumerAssociations", value) : undefined;
162
163 const toRangeActivation = (project: string, location: string, value: string | undefined) =>
164 value ? toNamedResource(project, location, "multicastGroupRangeActivations", value) : undefined;
165
166 const toGroup = (project: string, location: string, value: string | undefined) =>
167 value ? toNamedResource(project, location, "multicastGroups", value) : undefined;
168
169 const toLogConfig = (
170 config: MulticastLogConfig | networkservices.MulticastLogConfig | undefined,
171 ): MulticastLogConfig | undefined => {
172 if (config === undefined) return undefined;
173 return { enabled: config.enabled };
174 };
175
176 const toAttrs = (activation: networkservices.MulticastGroupConsumerActivation, project: string) => {
177 const name = activation.name ?? "";
178 const parsed = parseName(name, COLLECTION, DEFAULT_ZONE);
179 const location = parsed.location || DEFAULT_ZONE;
180 const proj = parsed.project || project;
181 return {
182 name,
183 multicastGroupConsumerActivationId: parsed.id,
184 project: proj,
185 location,
186 multicastConsumerAssociation: toAssociation(
187 proj,
188 location,
189 activation.multicastConsumerAssociation,
190 ),
191 multicastGroupRangeActivation: toRangeActivation(
192 proj,
193 location,
194 activation.multicastGroupRangeActivation,
195 ),
196 multicastGroup: toGroup(proj, location, activation.multicastGroup),
197 description: activation.description,
198 logConfig: toLogConfig(activation.logConfig),
199 resourceState: activation.resourceState,
200 state: activation.state?.state,
201 uniqueId: activation.uniqueId,
202 labels: userLabels(activation.labels),
203 createTime: activation.createTime,
204 updateTime: activation.updateTime,
205 };
206 };
207
208 const getByName = (name: string) =>
209 networkservices
210 .getProjectsLocationsMulticastGroupConsumerActivations({ name })
211 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
212
213 export const MulticastGroupConsumerActivationProvider = () =>
214 Provider.succeed(MulticastGroupConsumerActivation, {
215 stables: [
216 "name",
217 "multicastGroupConsumerActivationId",
218 "project",
219 "location",
220 "multicastConsumerAssociation",
221 "multicastGroupRangeActivation",
222 "uniqueId",
223 "createTime",
224 ],
225
226 diff: Effect.fn(function* ({ news, olds, output }) {
227 if (!isResolved(news)) return undefined;
228 const previousId =
229 olds?.multicastGroupConsumerActivationId ?? output?.multicastGroupConsumerActivationId;
230 const nextId = news.multicastGroupConsumerActivationId
231 ? rfc1035(news.multicastGroupConsumerActivationId, "mcast-gca", MAX_MULTICAST_NAME_LENGTH)
232 : previousId;
233 const previousLocation = normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE);
234 const nextLocation = normalizeLocation(
235 news.location ?? olds?.location ?? output?.location,
236 DEFAULT_ZONE,
237 );
238 const previousAssociation = linkKey(
239 olds?.multicastConsumerAssociation ?? output?.multicastConsumerAssociation,
240 );
241 const nextAssociation = linkKey(news.multicastConsumerAssociation);
242 const previousRange = linkKey(
243 olds?.multicastGroupRangeActivation ?? output?.multicastGroupRangeActivation,
244 );
245 const nextRange = linkKey(news.multicastGroupRangeActivation);
246 if (
247 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
248 previousLocation !== nextLocation ||
249 (previousAssociation.length > 0 && previousAssociation !== nextAssociation) ||
250 (previousRange.length > 0 && previousRange !== nextRange)
251 ) {
252 return { action: "replace" as const };
253 }
254 return undefined;
255 }),
256
257 read: Effect.fn(function* ({ id, olds, output }) {
258 const env = yield* GcpEnvironment.current;
259 const multicastGroupConsumerActivationId = yield* toPhysicalId(
260 id,
261 olds?.multicastGroupConsumerActivationId,
262 output?.multicastGroupConsumerActivationId,
263 "mcast-gca",
264 MAX_MULTICAST_NAME_LENGTH,
265 );
266 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE);
267 const name =
268 output?.name ??
269 resourceName(env.project, location, COLLECTION, multicastGroupConsumerActivationId);
270 const existing = yield* getByName(name);
271 if (existing === undefined) return undefined;
272 const attrs = toAttrs(existing, env.project);
273 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
274 }),
275
276 list: () =>
277 Effect.gen(function* () {
278 const env = yield* GcpEnvironment.current;
279 const items = yield* collectPages(
280 networkservices.listProjectsLocationsMulticastGroupConsumerActivations.pages({
281 parent: parentOf(env.project, "-"),
282 pageSize: 1000,
283 }),
284 (page) => page.multicastGroupConsumerActivations,
285 );
286 return items
287 .filter((item) => hasAlchemyLabelKeys(item.labels))
288 .map((item) => toAttrs(item, env.project));
289 }),
290
291 reconcile: Effect.fn(function* ({ id, news, output }) {
292 const env = yield* GcpEnvironment.current;
293 const multicastGroupConsumerActivationId = yield* toPhysicalId(
294 id,
295 news.multicastGroupConsumerActivationId,
296 output?.multicastGroupConsumerActivationId,
297 "mcast-gca",
298 MAX_MULTICAST_NAME_LENGTH,
299 );
300 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_ZONE);
301 const name = resourceName(
302 env.project,
303 location,
304 COLLECTION,
305 multicastGroupConsumerActivationId,
306 );
307 const desiredLabels = {
308 ...toLabels(news.labels),
309 ...(yield* createInternalLabels(id)),
310 };
311 const multicastConsumerAssociation = toAssociation(
312 env.project,
313 location,
314 news.multicastConsumerAssociation,
315 );
316 const multicastGroupRangeActivation = toRangeActivation(
317 env.project,
318 location,
319 news.multicastGroupRangeActivation,
320 );
321 const multicastGroup = toGroup(env.project, location, news.multicastGroup);
322 const logConfig = toLogConfig(news.logConfig);
323
324 let current = yield* getByName(name);
325
326 if (current === undefined) {
327 const created = yield* networkservices
328 .createProjectsLocationsMulticastGroupConsumerActivations({
329 parent: parentOf(env.project, location),
330 multicastGroupConsumerActivationId,
331 body: {
332 description: news.description,
333 labels: desiredLabels,
334 multicastConsumerAssociation,
335 multicastGroupRangeActivation,
336 multicastGroup,
337 logConfig,
338 },
339 })
340 .pipe(
341 Effect.retry({
342 while: (error) => error._tag === "Conflict",
343 times: 5,
344 schedule: Schedule.spaced("2 seconds"),
345 }),
346 Effect.catchTag("Conflict", () => Effect.undefined),
347 );
348 if (created !== undefined) {
349 yield* waitForOperation(created);
350 }
351 current = yield* waitUntilPresent(getByName(name), name);
352 }
353
354 const observed = toAttrs(current, env.project);
355 const observedLabels = tagRecord(current.labels);
356 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
357 const labelsChanged = upsert.length > 0 || removed.length > 0;
358 const updateMask = changedFields([
359 ["labels", labelsChanged],
360 ["description", (current.description ?? "") !== (news.description ?? "")],
361 ["logConfig", !sameJson(observed.logConfig, logConfig)],
362 ]);
363
364 if (updateMask.length > 0) {
365 const operation =
366 yield* networkservices.patchProjectsLocationsMulticastGroupConsumerActivations({
367 name: current.name ?? name,
368 updateMask: updateMask.join(","),
369 body: {
370 name: current.name ?? name,
371 labels: desiredLabels,
372 description: news.description,
373 logConfig,
374 },
375 });
376 yield* waitForOperation(operation);
377 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
378 }
379
380 return toAttrs(current, env.project);
381 }),
382
383 delete: Effect.fn(function* ({ output }) {
384 const operation = yield* networkservices
385 .deleteProjectsLocationsMulticastGroupConsumerActivations({
386 name: output.name,
387 })
388 .pipe(
389 Effect.retry({
390 while: (error) => error._tag === "Conflict",
391 times: 8,
392 schedule: Schedule.spaced("2 seconds"),
393 }),
394 Effect.catchTag("NotFound", () => Effect.undefined),
395 );
396 if (operation !== undefined) {
397 yield* waitForOperation(operation, { notFoundOk: true });
398 }
399 yield* waitUntilGone(getByName(output.name), output.name);
400 }),
401 });