@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 267 lines 9.12 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_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 { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 collectPages,
12 createOwnership,
13 defaultOrgName,
14 encodeDescription,
15 hasOwnershipMarker,
16 lastSegment,
17 letterPrefixedId,
18 listOrgNames,
19 orgIdOf,
20 orgNameOf,
21 ownedBy,
22 parseDescription,
23 waitForOperation,
24 } from "./operations.ts";
25
26 export type DnsZonePeeringConfig = {
27 /** VPC network whose private DNS namespace Apigee peers with. */
28 targetNetworkId: string;
29 /** Project id that contains `targetNetworkId`. */
30 targetProjectId: string;
31 };
32
33 export type DnsZoneProps = {
34 /**
35 * Apigee organization id or `organizations/{org}`. Defaults to the
36 * current GCP project id. Immutable — changing it replaces the zone.
37 */
38 organization?: string;
39 /**
40 * DNS zone id (the `{dns_zone}` segment of
41 * `organizations/{org}/dnsZones/{dns_zone}`). Must be 1-63 characters,
42 * begin with a letter, end with a letter or digit, and contain only
43 * lowercase letters, digits, or dashes. If omitted, a unique name is
44 * generated. Immutable — changing it replaces the zone.
45 */
46 dnsZoneId?: string;
47 /**
48 * Domain name for hosts in this private zone (for example
49 * `example.com.`). Immutable — changing it replaces the zone.
50 */
51 domain: string;
52 /**
53 * DNS peering configuration. Immutable — changing it replaces the zone.
54 */
55 peeringConfig: DnsZonePeeringConfig;
56 /**
57 * Human-readable description (required by Apigee, max 1024 characters).
58 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
59 * from attributes.
60 */
61 description?: string;
62 };
63
64 export type DnsZone = Resource<
65 "GCP.Apigee.DnsZone",
66 DnsZoneProps,
67 {
68 /** Full resource name `organizations/{org}/dnsZones/{dns_zone}`. */
69 name: string;
70 /** DNS zone id (last path segment). */
71 dnsZoneId: string;
72 /** Apigee organization id. */
73 organization: string;
74 /** Peered domain. */
75 domain: string;
76 /** DNS peering configuration. */
77 peeringConfig: DnsZonePeeringConfig | undefined;
78 /** User description with the Alchemy ownership prefix stripped. */
79 description: string | undefined;
80 /** Server-reported state (`CREATING`, `ACTIVE`, …). */
81 state: string | undefined;
82 /** RFC3339 creation timestamp. */
83 createTime: string | undefined;
84 /** RFC3339 last-update timestamp. */
85 updateTime: string | undefined;
86 },
87 never,
88 Providers
89 >;
90
91 /**
92 * An Apigee DNS peering zone that lets runtime instances resolve hostnames
93 * in a peered VPC.
94 *
95 * Apigee DNS zones have no labels field, so Alchemy stamps ownership into
96 * the description for `list` / nuke. Name, domain, and peering config are
97 * identity — changing them replaces the zone. Description updates in place
98 * only if the API later exposes a patch; today the resource is
99 * existence-only besides identity.
100 *
101 * ### Creating a DNS Zone
102 * **Example:** Peer with the default VPC
103 * ```typescript
104 * const zone = yield* GCP.Apigee.DnsZone("PrivateDns", {
105 * domain: "internal.example.com.",
106 * peeringConfig: {
107 * targetNetworkId: "default",
108 * targetProjectId: "my-project",
109 * },
110 * description: "runtime DNS peering",
111 * });
112 * ```
113 *
114 * @resource
115 * @category Apigee
116 */
117 export const DnsZone = Resource<DnsZone>("GCP.Apigee.DnsZone");
118
119 /** Alias matching the catalog name `Dn`. */
120 export const Dn = DnsZone;
121
122 export class DnsZoneNotResolved extends Data.TaggedError("GCP.Apigee.DnsZoneNotResolved")<{
123 resourceName: string;
124 }> {}
125
126 const resourceName = (organization: string, dnsZoneId: string) =>
127 `${orgNameOf(organization)}/dnsZones/${dnsZoneId}`;
128
129 const toAttrs = (zone: apigee.GoogleCloudApigeeV1DnsZone, organization: string) => {
130 const name = zone.name ?? "";
131 const parsed = parseDescription(zone.description);
132 const peering = zone.peeringConfig;
133 return {
134 name,
135 dnsZoneId: lastSegment(name),
136 organization: orgIdOf(organization),
137 domain: zone.domain ?? "",
138 peeringConfig:
139 peering?.targetNetworkId !== undefined || peering?.targetProjectId !== undefined
140 ? {
141 targetNetworkId: peering.targetNetworkId ?? "",
142 targetProjectId: peering.targetProjectId ?? "",
143 }
144 : undefined,
145 description: parsed.description,
146 state: zone.state,
147 createTime: zone.createTime,
148 updateTime: zone.updateTime,
149 };
150 };
151
152 const getByName = (name: string) =>
153 apigee
154 .getOrganizationsDnsZones({ name })
155 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
156
157 export const DnsZoneProvider = () =>
158 Provider.succeed(DnsZone, {
159 stables: ["name", "dnsZoneId", "organization", "domain", "createTime"],
160
161 diff: Effect.fn(function* ({ news, olds, output }) {
162 if (!isResolved(news)) return undefined;
163 const previousId = olds?.dnsZoneId ?? output?.dnsZoneId;
164 const previousOrg = olds?.organization ?? output?.organization;
165 const previousDomain = olds?.domain ?? output?.domain;
166 const previousPeer = olds?.peeringConfig ?? output?.peeringConfig;
167 const idChanged =
168 previousId !== undefined && news.dnsZoneId !== undefined && news.dnsZoneId !== previousId;
169 const orgChanged =
170 previousOrg !== undefined &&
171 news.organization !== undefined &&
172 orgIdOf(news.organization) !== orgIdOf(previousOrg);
173 const domainChanged = previousDomain !== undefined && news.domain !== previousDomain;
174 const peerChanged =
175 previousPeer !== undefined &&
176 (previousPeer.targetNetworkId !== news.peeringConfig.targetNetworkId ||
177 previousPeer.targetProjectId !== news.peeringConfig.targetProjectId);
178 if (idChanged || orgChanged || domainChanged || peerChanged) {
179 return {
180 action: "replace" as const,
181 deleteFirst: idChanged && !orgChanged,
182 };
183 }
184 return undefined;
185 }),
186
187 read: Effect.fn(function* ({ id, olds, output }) {
188 const env = yield* GcpEnvironment.current;
189 const organization = defaultOrgName(env.project, olds?.organization ?? output?.organization);
190 const dnsZoneId = yield* letterPrefixedId(id, olds?.dnsZoneId, output?.dnsZoneId, 63);
191 const name = output?.name ?? resourceName(organization, dnsZoneId);
192 const existing = yield* getByName(name);
193 if (existing === undefined) return undefined;
194 const attrs = toAttrs(existing, organization);
195 const { labels } = parseDescription(existing.description);
196 return (yield* ownedBy(id, labels)) ? attrs : Unowned(attrs);
197 }),
198
199 list: () =>
200 Effect.gen(function* () {
201 const orgs = yield* listOrgNames();
202 const rows: DnsZone["Attributes"][] = [];
203 for (const organization of orgs) {
204 const zones = yield* collectPages(
205 apigee.listOrganizationsDnsZones.pages({
206 parent: organization,
207 pageSize: 1000,
208 }),
209 (page) => page.dnsZones,
210 ).pipe(
211 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
212 Effect.succeed([] as apigee.GoogleCloudApigeeV1DnsZone[]),
213 ),
214 );
215 for (const zone of zones) {
216 if (hasOwnershipMarker(zone.description)) {
217 rows.push(toAttrs(zone, organization));
218 }
219 }
220 }
221 return rows;
222 }),
223
224 reconcile: Effect.fn(function* ({ id, news, output }) {
225 const env = yield* GcpEnvironment.current;
226 const organization = defaultOrgName(env.project, news.organization);
227 const dnsZoneId = yield* letterPrefixedId(id, news.dnsZoneId, output?.dnsZoneId, 63);
228 const name = resourceName(organization, dnsZoneId);
229 const ownership = yield* createOwnership(id);
230 const desiredDescription = encodeDescription(ownership, news.description);
231
232 let current = yield* getByName(output?.name ?? name);
233
234 if (current === undefined) {
235 const operation = yield* apigee
236 .createOrganizationsDnsZones({
237 parent: organization,
238 dnsZoneId,
239 body: {
240 description: desiredDescription,
241 domain: news.domain,
242 peeringConfig: news.peeringConfig,
243 },
244 })
245 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
246 if (operation !== undefined) {
247 yield* waitForOperation(operation);
248 }
249 current = yield* getByName(name);
250 }
251
252 if (current === undefined) {
253 return yield* new DnsZoneNotResolved({ resourceName: name });
254 }
255
256 return toAttrs(current, organization);
257 }),
258
259 delete: Effect.fn(function* ({ output }) {
260 const operation = yield* apigee
261 .deleteOrganizationsDnsZones({ name: output.name })
262 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
263 if (operation !== undefined) {
264 yield* waitForOperation(operation, { notFoundOk: true });
265 }
266 }),
267 });