@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 298 lines 10.2 KB
Raw
1 import * as managedidentities from "@distilled.cloud/gcp/managedidentities_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 domainResourceOf,
14 fieldMask,
15 globalParent,
16 listPeerings,
17 networkOf,
18 parseName,
19 replaceOnIdentity,
20 ResourceNotResolved,
21 toPhysicalId,
22 userLabels,
23 waitForOperation,
24 waitUntilExists,
25 waitUntilGone,
26 waitUntilReady,
27 } from "./internal.ts";
28
29 export type PeeringProps = {
30 /**
31 * Peering id (the `{peering}` segment of
32 * `projects/{project}/locations/global/peerings/{peering}`). If omitted,
33 * a unique RFC1035 name is generated from the stack, stage, and logical
34 * id. Must match `^[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?$`. Immutable —
35 * changing it replaces the peering.
36 */
37 peeringId?: string;
38 /**
39 * Managed Microsoft AD domain to peer with. Must live in a different
40 * project than `authorizedNetwork`. Full name
41 * `projects/{project}/locations/global/domains/{domain}` or the domain
42 * FQDN. Immutable — changing it replaces the peering.
43 */
44 domainResource: string;
45 /**
46 * VPC network the domain is peered into, as an id (`default`) or full
47 * name (`projects/{project}/global/networks/{network}`). Caller must
48 * ensure CIDR subnets do not overlap the domain. Immutable — changing
49 * it replaces the peering.
50 */
51 authorizedNetwork: string;
52 /**
53 * User labels. Alchemy ownership labels are merged in automatically.
54 * Labels are the only mutable field.
55 */
56 labels?: Record<string, string>;
57 };
58
59 export type Peering = Resource<
60 "GCP.ManagedIdentities.Peering",
61 PeeringProps,
62 {
63 /** Full resource name `projects/{project}/locations/global/peerings/{peering}`. */
64 name: string;
65 /** Peering id (last path segment). */
66 peeringId: string;
67 /** Project id. */
68 project: string;
69 /** Resource location (`global`). */
70 location: string;
71 /** Peered domain resource name. */
72 domainResource: string | undefined;
73 /** Authorized VPC network. */
74 authorizedNetwork: string | undefined;
75 /** User labels (Alchemy ownership labels stripped). */
76 labels: Record<string, string>;
77 /** Server-reported state (`CONNECTED`, `CREATING`, …). */
78 state: string | undefined;
79 /** Additional status information, if available. */
80 statusMessage: string | undefined;
81 /** RFC3339 creation timestamp. */
82 createTime: string | undefined;
83 /** RFC3339 last-update timestamp. */
84 updateTime: string | undefined;
85 },
86 never,
87 Providers
88 >;
89
90 /**
91 * A Managed Microsoft AD domain peering — attaches a VPC in this
92 * project to a Managed AD domain that lives in a **different** project
93 * so VMs on that network can join the domain. Same-project access uses
94 * `Domain.authorizedNetworks` instead; creating a peering when domain
95 * and network share a project is rejected with `BadRequest`.
96 *
97 * Changing `peeringId`, `domainResource`, or `authorizedNetwork`
98 * replaces the peering. Labels update in place.
99 *
100 * ### Creating a Peering
101 * **Example:** Generated name
102 * ```typescript
103 * const peering = yield* GCP.ManagedIdentities.Peering("Spoke", {
104 * domainResource: domain.name,
105 * authorizedNetwork: "default",
106 * });
107 * ```
108 *
109 * **Example:** Explicit id and labels
110 * ```typescript
111 * const peering = yield* GCP.ManagedIdentities.Peering("Spoke", {
112 * peeringId: "app-spoke",
113 * domainResource: domain.name,
114 * authorizedNetwork: "projects/my-project/global/networks/default",
115 * labels: { env: "prod" },
116 * });
117 * ```
118 *
119 * ### Updating a Peering
120 * Re-declare the same logical id with changed props; the engine keeps the
121 * physical resource and updates it in place.
122 *
123 * **Example:** Labels
124 * ```typescript
125 * const peering = yield* GCP.ManagedIdentities.Peering("Spoke", {
126 * domainResource: domain.name,
127 * authorizedNetwork: "default",
128 * labels: { env: "prod", team: "identity" },
129 * });
130 * ```
131 *
132 * @resource
133 * @category ManagedIdentities
134 */
135 export const Peering = Resource<Peering>("GCP.ManagedIdentities.Peering");
136
137 const resourceName = (project: string, peeringId: string) =>
138 `${globalParent(project)}/peerings/${peeringId}`;
139
140 const toAttrs = (item: managedidentities.Peering, project: string) => {
141 const name = item.name ?? "";
142 const parsed = parseName(name, "peerings");
143 return {
144 name,
145 peeringId: parsed.id,
146 project: parsed.project || project,
147 location: parsed.location,
148 domainResource: item.domainResource,
149 authorizedNetwork: item.authorizedNetwork,
150 labels: userLabels(item.labels),
151 state: item.state,
152 statusMessage: item.statusMessage,
153 createTime: item.createTime,
154 updateTime: item.updateTime,
155 };
156 };
157
158 const getByName = (name: string) =>
159 name.length === 0
160 ? Effect.undefined
161 : managedidentities
162 .getProjectsLocationsGlobalPeerings({ name })
163 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
164
165 export const PeeringProvider = () =>
166 Provider.succeed(Peering, {
167 stables: ["name", "peeringId", "project", "location", "createTime"],
168
169 diff: Effect.fn(function* ({ news, olds, output }) {
170 if (!isResolved(news)) return undefined;
171 const env = yield* GcpEnvironment.current;
172 const previousDomain = domainResourceOf(
173 olds?.domainResource ?? output?.domainResource ?? "",
174 env.project,
175 );
176 const nextDomain = domainResourceOf(
177 news.domainResource ?? olds?.domainResource ?? output?.domainResource ?? "",
178 env.project,
179 );
180 const previousNetwork = networkOf(
181 olds?.authorizedNetwork ?? output?.authorizedNetwork ?? "",
182 env.project,
183 );
184 const nextNetwork = networkOf(
185 news.authorizedNetwork ?? olds?.authorizedNetwork ?? output?.authorizedNetwork ?? "",
186 env.project,
187 );
188 return replaceOnIdentity({
189 previousId: olds?.peeringId ?? output?.peeringId,
190 nextId: news.peeringId ?? olds?.peeringId ?? output?.peeringId,
191 extra:
192 (previousDomain.length > 0 && nextDomain.length > 0 && previousDomain !== nextDomain) ||
193 (previousNetwork.length > 0 && nextNetwork.length > 0 && previousNetwork !== nextNetwork),
194 });
195 }),
196
197 read: Effect.fn(function* ({ id, olds, output }) {
198 const env = yield* GcpEnvironment.current;
199 const peeringId = yield* toPhysicalId(id, olds?.peeringId, output?.peeringId, "peering");
200 const name = output?.name ?? resourceName(env.project, peeringId);
201 const existing = yield* getByName(name);
202 if (existing === undefined) return undefined;
203 const attrs = toAttrs(existing, env.project);
204 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
205 }),
206
207 list: () =>
208 Effect.gen(function* () {
209 const env = yield* GcpEnvironment.current;
210 const items = yield* listPeerings(env.project);
211 return items.map((item) => toAttrs(item, env.project));
212 }),
213
214 reconcile: Effect.fn(function* ({ id, news, output }) {
215 const env = yield* GcpEnvironment.current;
216 const peeringId = yield* toPhysicalId(id, news.peeringId, output?.peeringId, "peering");
217 const name = resourceName(env.project, peeringId);
218 const domainResource = domainResourceOf(news.domainResource, env.project);
219 const authorizedNetwork = networkOf(news.authorizedNetwork, env.project);
220 const desiredLabels = {
221 ...toLabels(news.labels),
222 ...(yield* createInternalLabels(id)),
223 };
224
225 let current = yield* getByName(output?.name ?? name);
226
227 if (current === undefined) {
228 const created = yield* managedidentities
229 .createProjectsLocationsGlobalPeerings({
230 parent: globalParent(env.project),
231 peeringId,
232 body: {
233 domainResource,
234 authorizedNetwork,
235 labels: desiredLabels,
236 },
237 })
238 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
239 if (created !== undefined) {
240 yield* waitForOperation(created);
241 }
242 current = yield* waitUntilExists(getByName(name), name);
243 }
244
245 if (current === undefined) {
246 return yield* new ResourceNotResolved({ resourceName: name });
247 }
248
249 current = yield* waitUntilReady(
250 getByName(current.name ?? name),
251 current.name ?? name,
252 (item: managedidentities.Peering) => item.state,
253 (item: managedidentities.Peering) => item.statusMessage,
254 );
255
256 const observedLabels = tagRecord(current.labels);
257 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
258 const mask = fieldMask([(upsert.length > 0 || removed.length > 0) && "labels"]);
259
260 if (mask.length > 0) {
261 const operation = yield* managedidentities.patchProjectsLocationsGlobalPeerings({
262 name: current.name ?? name,
263 updateMask: mask,
264 body: {
265 name: current.name ?? name,
266 labels: desiredLabels,
267 },
268 });
269 yield* waitForOperation(operation);
270 current = yield* waitUntilReady(
271 getByName(current.name ?? name),
272 current.name ?? name,
273 (item: managedidentities.Peering) => item.state,
274 (item: managedidentities.Peering) => item.statusMessage,
275 );
276 }
277
278 return toAttrs(current, env.project);
279 }),
280
281 delete: Effect.fn(function* ({ output }) {
282 if (!output.name) return;
283 const operation = yield* managedidentities
284 .deleteProjectsLocationsGlobalPeerings({ name: output.name })
285 .pipe(
286 Effect.retry({
287 while: (error) => error._tag === "Conflict",
288 times: 8,
289 schedule: Schedule.spaced("2 seconds"),
290 }),
291 Effect.catchTag("NotFound", () => Effect.undefined),
292 );
293 if (operation !== undefined) {
294 yield* waitForOperation(operation, { notFoundOk: true });
295 }
296 yield* waitUntilGone(getByName(output.name), output.name);
297 }),
298 });