@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 342 lines 12.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 toMulticastNetwork,
25 toNamedResource,
26 toPhysicalId,
27 userLabels,
28 waitForOperation,
29 waitUntilGone,
30 waitUntilPresent,
31 } from "./internal.ts";
32
33 const COLLECTION = "multicastConsumerAssociations";
34
35 export type MulticastConsumerAssociationProps = {
36 /**
37 * Association id (the `{multicastConsumerAssociation}` segment of
38 * `projects/{project}/locations/{location}/multicastConsumerAssociations/{multicastConsumerAssociation}`).
39 * If omitted, a unique name is generated from the stack, stage, and
40 * logical id. Must be at most 48 characters. Immutable — changing it
41 * replaces the association.
42 */
43 multicastConsumerAssociationId?: string;
44 /**
45 * Zone of the association (`us-central1-a`, …). Immutable — changing
46 * it replaces the association. `US-CENTRAL1-A` is accepted and
47 * normalized to `us-central1-a`.
48 * @default "us-central1-a"
49 */
50 location?: string;
51 /**
52 * Consumer VPC network
53 * `projects/{project}/locations/global/networks/{network}`. Immutable
54 * — changing it replaces the association.
55 */
56 network: string;
57 /**
58 * Multicast domain activation in the same zone
59 * (`projects/{project}/locations/{location}/multicastDomainActivations/{activation}`).
60 * The live API currently requires this field. Immutable — changing it
61 * replaces the association.
62 */
63 multicastDomainActivation?: string;
64 /**
65 * Human-readable description.
66 */
67 description?: string;
68 /**
69 * User labels. Alchemy ownership labels are merged in automatically.
70 */
71 labels?: Record<string, string>;
72 };
73
74 export type MulticastConsumerAssociation = Resource<
75 "GCP.NetworkServices.MulticastConsumerAssociation",
76 MulticastConsumerAssociationProps,
77 {
78 /** Full resource name `projects/{project}/locations/{location}/multicastConsumerAssociations/{multicastConsumerAssociation}`. */
79 name: string;
80 /** Association id (last path segment). */
81 multicastConsumerAssociationId: string;
82 /** Project id. */
83 project: string;
84 /** Zone id (`us-central1-a`, …). */
85 location: string;
86 /** Consumer VPC network resource name. */
87 network: string | undefined;
88 /** Attached multicast domain activation, if set. */
89 multicastDomainActivation: string | undefined;
90 /** User-provided description. */
91 description: string | undefined;
92 /** Deprecated resource-state enum. */
93 resourceState: string | undefined;
94 /** Nested multicast resource state. */
95 state: string | undefined;
96 /** Google-generated UUID. */
97 uniqueId: string | undefined;
98 /** Placement-policy resource name, if set. */
99 placementPolicy: string | undefined;
100 /** User labels (Alchemy ownership labels stripped). */
101 labels: Record<string, string>;
102 /** RFC3339 creation timestamp. */
103 createTime: string | undefined;
104 /** RFC3339 last-update timestamp. */
105 updateTime: string | undefined;
106 },
107 never,
108 Providers
109 >;
110
111 /**
112 * A multicast consumer association attaches a consumer VPC to Cloud
113 * Multicast in a zone so VMs in that network can join multicast groups.
114 *
115 * Changing `multicastConsumerAssociationId`, `location`, `network`, or
116 * `multicastDomainActivation` replaces the association. Description and
117 * labels update in place.
118 *
119 * ### Creating a MulticastConsumerAssociation
120 * **Example:** Associate a VPC
121 * ```typescript
122 * const association = yield* GCP.NetworkServices.MulticastConsumerAssociation(
123 * "Consumers",
124 * {
125 * location: "us-central1-a",
126 * network: `projects/${vpc.project}/locations/global/networks/${vpc.networkName}`,
127 * labels: { env: "prod" },
128 * },
129 * );
130 * ```
131 *
132 * @resource
133 * @category NetworkServices
134 */
135 export const MulticastConsumerAssociation = Resource<MulticastConsumerAssociation>(
136 "GCP.NetworkServices.MulticastConsumerAssociation",
137 );
138
139 const toActivation = (project: string, location: string, value: string | undefined) =>
140 value ? toNamedResource(project, location, "multicastDomainActivations", value) : undefined;
141
142 const toAttrs = (association: networkservices.MulticastConsumerAssociation, project: string) => {
143 const name = association.name ?? "";
144 const parsed = parseName(name, COLLECTION, DEFAULT_ZONE);
145 const location = parsed.location || DEFAULT_ZONE;
146 const proj = parsed.project || project;
147 return {
148 name,
149 multicastConsumerAssociationId: parsed.id,
150 project: proj,
151 location,
152 network: association.network ? toMulticastNetwork(proj, association.network) : undefined,
153 multicastDomainActivation: toActivation(proj, location, association.multicastDomainActivation),
154 description: association.description,
155 resourceState: association.resourceState,
156 state: association.state?.state,
157 uniqueId: association.uniqueId,
158 placementPolicy: association.placementPolicy,
159 labels: userLabels(association.labels),
160 createTime: association.createTime,
161 updateTime: association.updateTime,
162 };
163 };
164
165 const getByName = (name: string) =>
166 networkservices
167 .getProjectsLocationsMulticastConsumerAssociations({ name })
168 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
169
170 export const MulticastConsumerAssociationProvider = () =>
171 Provider.succeed(MulticastConsumerAssociation, {
172 stables: [
173 "name",
174 "multicastConsumerAssociationId",
175 "project",
176 "location",
177 "network",
178 "multicastDomainActivation",
179 "uniqueId",
180 "createTime",
181 ],
182
183 diff: Effect.fn(function* ({ news, olds, output }) {
184 if (!isResolved(news)) return undefined;
185 const previousId =
186 olds?.multicastConsumerAssociationId ?? output?.multicastConsumerAssociationId;
187 const nextId = news.multicastConsumerAssociationId
188 ? rfc1035(news.multicastConsumerAssociationId, "mcast-assoc", MAX_MULTICAST_NAME_LENGTH)
189 : previousId;
190 const previousLocation = normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE);
191 const nextLocation = normalizeLocation(
192 news.location ?? olds?.location ?? output?.location,
193 DEFAULT_ZONE,
194 );
195 const previousNetwork = linkKey(olds?.network ?? output?.network);
196 const nextNetwork = linkKey(news.network);
197 const previousActivation = linkKey(
198 olds?.multicastDomainActivation ?? output?.multicastDomainActivation,
199 );
200 const nextActivation = linkKey(news.multicastDomainActivation);
201 if (
202 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
203 previousLocation !== nextLocation ||
204 (previousNetwork.length > 0 && previousNetwork !== nextNetwork) ||
205 (previousActivation.length > 0 &&
206 nextActivation.length > 0 &&
207 previousActivation !== nextActivation)
208 ) {
209 return { action: "replace" as const };
210 }
211 return undefined;
212 }),
213
214 read: Effect.fn(function* ({ id, olds, output }) {
215 const env = yield* GcpEnvironment.current;
216 const multicastConsumerAssociationId = yield* toPhysicalId(
217 id,
218 olds?.multicastConsumerAssociationId,
219 output?.multicastConsumerAssociationId,
220 "mcast-assoc",
221 MAX_MULTICAST_NAME_LENGTH,
222 );
223 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE);
224 const name =
225 output?.name ??
226 resourceName(env.project, location, COLLECTION, multicastConsumerAssociationId);
227 const existing = yield* getByName(name);
228 if (existing === undefined) return undefined;
229 const attrs = toAttrs(existing, env.project);
230 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
231 }),
232
233 list: () =>
234 Effect.gen(function* () {
235 const env = yield* GcpEnvironment.current;
236 const items = yield* collectPages(
237 networkservices.listProjectsLocationsMulticastConsumerAssociations.pages({
238 parent: parentOf(env.project, "-"),
239 pageSize: 1000,
240 }),
241 (page) => page.multicastConsumerAssociations,
242 );
243 return items
244 .filter((item) => hasAlchemyLabelKeys(item.labels))
245 .map((item) => toAttrs(item, env.project));
246 }),
247
248 reconcile: Effect.fn(function* ({ id, news, output }) {
249 const env = yield* GcpEnvironment.current;
250 const multicastConsumerAssociationId = yield* toPhysicalId(
251 id,
252 news.multicastConsumerAssociationId,
253 output?.multicastConsumerAssociationId,
254 "mcast-assoc",
255 MAX_MULTICAST_NAME_LENGTH,
256 );
257 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_ZONE);
258 const name = resourceName(env.project, location, COLLECTION, multicastConsumerAssociationId);
259 const desiredLabels = {
260 ...toLabels(news.labels),
261 ...(yield* createInternalLabels(id)),
262 };
263 const network = toMulticastNetwork(env.project, news.network);
264 const multicastDomainActivation = toActivation(
265 env.project,
266 location,
267 news.multicastDomainActivation,
268 );
269
270 let current = yield* getByName(name);
271
272 if (current === undefined) {
273 const created = yield* networkservices
274 .createProjectsLocationsMulticastConsumerAssociations({
275 parent: parentOf(env.project, location),
276 multicastConsumerAssociationId,
277 body: {
278 description: news.description,
279 labels: desiredLabels,
280 network,
281 multicastDomainActivation,
282 },
283 })
284 .pipe(
285 Effect.retry({
286 while: (error) => error._tag === "Conflict",
287 times: 5,
288 schedule: Schedule.spaced("2 seconds"),
289 }),
290 Effect.catchTag("Conflict", () => Effect.undefined),
291 );
292 if (created !== undefined) {
293 yield* waitForOperation(created);
294 }
295 current = yield* waitUntilPresent(getByName(name), name);
296 }
297
298 const observedLabels = tagRecord(current.labels);
299 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
300 const labelsChanged = upsert.length > 0 || removed.length > 0;
301 const updateMask = changedFields([
302 ["labels", labelsChanged],
303 ["description", (current.description ?? "") !== (news.description ?? "")],
304 ]);
305
306 if (updateMask.length > 0) {
307 const operation =
308 yield* networkservices.patchProjectsLocationsMulticastConsumerAssociations({
309 name: current.name ?? name,
310 updateMask: updateMask.join(","),
311 body: {
312 name: current.name ?? name,
313 labels: desiredLabels,
314 description: news.description,
315 },
316 });
317 yield* waitForOperation(operation);
318 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
319 }
320
321 return toAttrs(current, env.project);
322 }),
323
324 delete: Effect.fn(function* ({ output }) {
325 const operation = yield* networkservices
326 .deleteProjectsLocationsMulticastConsumerAssociations({
327 name: output.name,
328 })
329 .pipe(
330 Effect.retry({
331 while: (error) => error._tag === "Conflict",
332 times: 8,
333 schedule: Schedule.spaced("2 seconds"),
334 }),
335 Effect.catchTag("NotFound", () => Effect.undefined),
336 );
337 if (operation !== undefined) {
338 yield* waitForOperation(operation, { notFoundOk: true });
339 }
340 yield* waitUntilGone(getByName(output.name), output.name);
341 }),
342 });