@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 354 lines 12.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 DEFAULT_ADMIN,
14 DEFAULT_NETWORK,
15 domainNameOf,
16 fieldMask,
17 globalParent,
18 listDomains,
19 networkOf,
20 normalizeLocation,
21 parseName,
22 replaceOnIdentity,
23 ResourceNotResolved,
24 sameStringList,
25 toDomainName,
26 userLabels,
27 waitForOperation,
28 waitUntilExists,
29 waitUntilGone,
30 waitUntilReady,
31 } from "./internal.ts";
32
33 export type DomainProps = {
34 /**
35 * Fully-qualified domain name (the `{domain}` segment of
36 * `projects/{project}/locations/global/domains/{domain}`). Example:
37 * `corp.example.com`. If omitted, a unique FQDN is generated from the
38 * stack, stage, and logical id (`{id}.alch.test`). Must be 2-64
39 * characters, start with a letter, use only lowercase letters, numbers,
40 * periods, and hyphens, and the first label must be 15 characters or
41 * fewer. Immutable — changing it replaces the domain.
42 */
43 domainName?: string;
44 /**
45 * CIDR of internal addresses reserved for this domain (`10.0.1.0/24`).
46 * Must be `/24` or larger and must not overlap subnets in
47 * `authorizedNetworks`. Immutable — changing it replaces the domain.
48 */
49 reservedIpRange: string;
50 /**
51 * Regions where domain controllers are provisioned (`us-central1`,
52 * `us-east4`, …). Up to 4. `US-CENTRAL1` is accepted and normalized to
53 * `us-central1`.
54 * @default [the stack's GCP region] (`GCP.Region`, else the profile
55 * region, else `us-central1`)
56 */
57 locations?: string[];
58 /**
59 * VPC networks the domain is reachable from, as ids (`default`) or
60 * full names (`projects/{project}/global/networks/{network}`).
61 * @default ["default"]
62 */
63 authorizedNetworks?: string[];
64 /**
65 * Delegated administrator account used for Active Directory operations.
66 * Immutable — changing it replaces the domain.
67 * @default "setupadmin"
68 */
69 admin?: string;
70 /**
71 * Whether AD audit logs are enabled.
72 * @default false
73 */
74 auditLogsEnabled?: boolean;
75 /**
76 * User labels. Alchemy ownership labels are merged in automatically.
77 */
78 labels?: Record<string, string>;
79 };
80
81 export type Domain = Resource<
82 "GCP.ManagedIdentities.Domain",
83 DomainProps,
84 {
85 /** Full resource name `projects/{project}/locations/global/domains/{domain}`. */
86 name: string;
87 /** Fully-qualified domain name (last path segment). */
88 domainName: string;
89 /** Project id. */
90 project: string;
91 /** Resource location (`global`). */
92 location: string;
93 /** Reserved CIDR for the domain. */
94 reservedIpRange: string | undefined;
95 /** Regions where domain controllers are provisioned. */
96 locations: string[];
97 /** Authorized VPC networks. */
98 authorizedNetworks: string[];
99 /** Delegated administrator account. */
100 admin: string | undefined;
101 /** Whether AD audit logs are enabled. */
102 auditLogsEnabled: boolean;
103 /** User labels (Alchemy ownership labels stripped). */
104 labels: Record<string, string>;
105 /** Exposed Active Directory FQDN clients use to connect. */
106 fqdn: string | undefined;
107 /** Current trusts associated with the domain. */
108 trusts: managedidentities.Trust[];
109 /** Server-reported state (`READY`, `CREATING`, …). */
110 state: string | undefined;
111 /** Additional status information, if available. */
112 statusMessage: string | undefined;
113 /** RFC3339 creation timestamp. */
114 createTime: string | undefined;
115 /** RFC3339 last-update timestamp. */
116 updateTime: string | undefined;
117 },
118 never,
119 Providers
120 >;
121
122 /**
123 * A Managed Microsoft Active Directory domain.
124 *
125 * Changing `domainName`, `reservedIpRange`, or `admin` replaces the
126 * domain. `locations`, `authorizedNetworks`, `auditLogsEnabled`, and
127 * `labels` update in place. Provisioning typically takes 20-60 minutes.
128 *
129 * ### Creating a Domain
130 * **Example:** Generated FQDN
131 * ```typescript
132 * const domain = yield* GCP.ManagedIdentities.Domain("Corp", {
133 * reservedIpRange: "172.16.0.0/24",
134 * locations: ["us-central1"],
135 * });
136 * ```
137 *
138 * **Example:** Explicit FQDN, networks, and labels
139 * ```typescript
140 * const domain = yield* GCP.ManagedIdentities.Domain("Corp", {
141 * domainName: "corp.example.com",
142 * reservedIpRange: "172.16.0.0/24",
143 * locations: ["us-central1"],
144 * authorizedNetworks: ["default"],
145 * auditLogsEnabled: true,
146 * labels: { env: "prod" },
147 * });
148 * ```
149 *
150 * ### Updating a Domain
151 * Re-declare the same logical id with changed props; the engine keeps the
152 * physical resource and updates it in place.
153 *
154 * **Example:** Labels and audit logs
155 * ```typescript
156 * const domain = yield* GCP.ManagedIdentities.Domain("Corp", {
157 * domainName: "corp.example.com",
158 * reservedIpRange: "172.16.0.0/24",
159 * locations: ["us-central1"],
160 * auditLogsEnabled: true,
161 * labels: { env: "prod", team: "identity" },
162 * });
163 * ```
164 *
165 * @resource
166 * @category ManagedIdentities
167 */
168 export const Domain = Resource<Domain>("GCP.ManagedIdentities.Domain");
169
170 const resourceName = (project: string, domainName: string) =>
171 `${globalParent(project)}/domains/${domainName}`;
172
173 const locationsOf = (values: readonly string[] | undefined, defaultLocation: string) =>
174 (values ?? [defaultLocation]).map(normalizeLocation);
175
176 const networksOf = (values: readonly string[] | undefined, project: string) =>
177 (values ?? [DEFAULT_NETWORK]).map((value) => networkOf(value, project));
178
179 const adminOf = (value: string | undefined) => value || DEFAULT_ADMIN;
180
181 const toAttrs = (item: managedidentities.Domain, project: string) => {
182 const name = item.name ?? "";
183 const parsed = parseName(name, "domains");
184 return {
185 name,
186 domainName: parsed.id,
187 project: parsed.project || project,
188 location: parsed.location,
189 reservedIpRange: item.reservedIpRange,
190 locations: item.locations ?? [],
191 authorizedNetworks: item.authorizedNetworks ?? [],
192 admin: item.admin,
193 auditLogsEnabled: item.auditLogsEnabled === true,
194 labels: userLabels(item.labels),
195 fqdn: item.fqdn,
196 trusts: item.trusts ?? [],
197 state: item.state,
198 statusMessage: item.statusMessage,
199 createTime: item.createTime,
200 updateTime: item.updateTime,
201 };
202 };
203
204 const getByName = (name: string) =>
205 name.length === 0
206 ? Effect.undefined
207 : managedidentities
208 .getProjectsLocationsGlobalDomains({ name })
209 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
210
211 export const DomainProvider = () =>
212 Provider.succeed(Domain, {
213 stables: ["name", "domainName", "project", "location", "createTime"],
214
215 diff: Effect.fn(function* ({ news, olds, output }) {
216 if (!isResolved(news)) return undefined;
217 const previousName = domainNameOf(
218 olds?.domainName ?? output?.domainName ?? output?.name ?? "",
219 );
220 const nextName = domainNameOf(
221 news.domainName ?? olds?.domainName ?? output?.domainName ?? "",
222 );
223 const previousRange = olds?.reservedIpRange ?? output?.reservedIpRange;
224 const previousAdmin = adminOf(olds?.admin ?? output?.admin);
225 return replaceOnIdentity({
226 previousId: previousName.length > 0 ? previousName : undefined,
227 nextId: nextName.length > 0 ? nextName : undefined,
228 extra:
229 (previousRange !== undefined && news.reservedIpRange !== previousRange) ||
230 (news.admin !== undefined && adminOf(news.admin) !== previousAdmin),
231 });
232 }),
233
234 read: Effect.fn(function* ({ id, olds, output }) {
235 const env = yield* GcpEnvironment.current;
236 const domainName = yield* toDomainName(id, olds?.domainName, output?.domainName);
237 const name = output?.name ?? resourceName(env.project, domainName);
238 const existing = yield* getByName(name);
239 if (existing === undefined) return undefined;
240 const attrs = toAttrs(existing, env.project);
241 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
242 }),
243
244 list: () =>
245 Effect.gen(function* () {
246 const env = yield* GcpEnvironment.current;
247 const items = yield* listDomains(env.project);
248 return items.map((item) => toAttrs(item, env.project));
249 }),
250
251 reconcile: Effect.fn(function* ({ id, news, output }) {
252 const env = yield* GcpEnvironment.current;
253 const domainName = yield* toDomainName(id, news.domainName, output?.domainName);
254 const name = resourceName(env.project, domainName);
255 const desiredLabels = {
256 ...toLabels(news.labels),
257 ...(yield* createInternalLabels(id)),
258 };
259 const locations = locationsOf(news.locations ?? output?.locations, env.region);
260 const authorizedNetworks = networksOf(
261 news.authorizedNetworks ?? output?.authorizedNetworks,
262 env.project,
263 );
264 const auditLogsEnabled = news.auditLogsEnabled ?? false;
265
266 let current = yield* getByName(output?.name ?? name);
267
268 if (current === undefined) {
269 const created = yield* managedidentities
270 .createProjectsLocationsGlobalDomains({
271 parent: globalParent(env.project),
272 domainName,
273 body: {
274 reservedIpRange: news.reservedIpRange,
275 locations,
276 authorizedNetworks,
277 admin: news.admin,
278 auditLogsEnabled,
279 labels: desiredLabels,
280 },
281 })
282 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
283 if (created !== undefined) {
284 yield* waitForOperation(created);
285 }
286 current = yield* waitUntilExists(getByName(name), name);
287 }
288
289 if (current === undefined) {
290 return yield* new ResourceNotResolved({ resourceName: name });
291 }
292
293 current = yield* waitUntilReady(
294 getByName(current.name ?? name),
295 current.name ?? name,
296 (item: managedidentities.Domain) => item.state,
297 (item: managedidentities.Domain) => item.statusMessage,
298 );
299
300 const observedLabels = tagRecord(current.labels);
301 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
302 const observedNetworks = current.authorizedNetworks ?? [];
303 const observedLocations = current.locations ?? [];
304 const mask = fieldMask([
305 (upsert.length > 0 || removed.length > 0) && "labels",
306 !sameStringList(observedLocations, locations) && "locations",
307 news.authorizedNetworks !== undefined &&
308 !sameStringList(observedNetworks, authorizedNetworks) &&
309 "authorized_networks",
310 (current.auditLogsEnabled === true) !== auditLogsEnabled && "audit_logs_enabled",
311 ]);
312
313 if (mask.length > 0) {
314 const operation = yield* managedidentities.patchProjectsLocationsGlobalDomains({
315 name: current.name ?? name,
316 updateMask: mask,
317 body: {
318 name: current.name ?? name,
319 labels: desiredLabels,
320 locations,
321 authorizedNetworks,
322 auditLogsEnabled,
323 },
324 });
325 yield* waitForOperation(operation);
326 current = yield* waitUntilReady(
327 getByName(current.name ?? name),
328 current.name ?? name,
329 (item: managedidentities.Domain) => item.state,
330 (item: managedidentities.Domain) => item.statusMessage,
331 );
332 }
333
334 return toAttrs(current, env.project);
335 }),
336
337 delete: Effect.fn(function* ({ output }) {
338 if (!output.name) return;
339 const operation = yield* managedidentities
340 .deleteProjectsLocationsGlobalDomains({ name: output.name })
341 .pipe(
342 Effect.retry({
343 while: (error) => error._tag === "Conflict",
344 times: 8,
345 schedule: Schedule.spaced("5 seconds"),
346 }),
347 Effect.catchTag("NotFound", () => Effect.undefined),
348 );
349 if (operation !== undefined) {
350 yield* waitForOperation(operation, { notFoundOk: true });
351 }
352 yield* waitUntilGone(getByName(output.name), output.name);
353 }),
354 });