@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 392 lines 12.8 KB
Raw
1 import * as dns from "@distilled.cloud/gcp/dns_v1";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
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 { ALCHEMY_LABEL_PREFIX } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const MAX_NAME_LENGTH = 63;
13 const DEFAULT_TTL = 300;
14
15 export type ResponsePolicyRuleLocalData = {
16 /**
17 * DNS name for this record. Defaults to the rule's `dnsName`.
18 */
19 name?: string;
20 /**
21 * DNS record type (`A`, `AAAA`, `CNAME`, `TXT`, …). SOA and NS are
22 * not allowed.
23 */
24 type: string;
25 /**
26 * TTL in seconds.
27 * @default 300
28 */
29 ttl?: number;
30 /**
31 * Resource-record data.
32 */
33 rrdatas?: string[];
34 };
35
36 export type ResponsePolicyRuleBehavior = dns.ResponsePolicyRuleBehaviorEnum;
37
38 export type ResponsePolicyRuleProps = {
39 /**
40 * Response policy name that owns this rule. Immutable — changing it
41 * replaces the rule.
42 */
43 responsePolicy: string;
44 /**
45 * User-assigned rule name, unique within the response policy. If
46 * omitted, a unique RFC1035 name is generated from the stack, stage,
47 * and logical id. Immutable — changing it replaces the rule.
48 */
49 ruleName?: string;
50 /**
51 * DNS name (wildcard or exact) this rule matches, for instance
52 * `"internal.example.com."` or `"*.example.com."`. A trailing dot is
53 * added if omitted.
54 */
55 dnsName: string;
56 /**
57 * Local DNS answers that override private zones, public DNS, and GCP
58 * internal DNS for the matched name. Mutually exclusive with
59 * `behavior`.
60 */
61 localData?: ResponsePolicyRuleLocalData[];
62 /**
63 * Answer with a behavior instead of DNS data. `bypassResponsePolicy`
64 * skips this response policy (and falls through to ordinary DNS) for
65 * the matched name. Mutually exclusive with `localData`.
66 */
67 behavior?: ResponsePolicyRuleBehavior;
68 };
69
70 export type ResponsePolicyRule = Resource<
71 "GCP.DNS.ResponsePolicyRule",
72 ResponsePolicyRuleProps,
73 {
74 /** Project id. */
75 project: string;
76 /** Parent response policy name. */
77 responsePolicy: string;
78 /** User-assigned rule name. */
79 ruleName: string;
80 /** DNS name selector, with trailing dot. */
81 dnsName: string;
82 /** Local override records, if this is not a behavior rule. */
83 localData: ReadonlyArray<ResponsePolicyRuleLocalData>;
84 /** Behavior, if this is not a local-data rule. */
85 behavior: string | undefined;
86 /** Server-reported kind (`dns#responsePolicyRule`). */
87 kind: string | undefined;
88 },
89 never,
90 Providers
91 >;
92
93 /**
94 * A Cloud DNS response policy rule.
95 *
96 * Identity is `(responsePolicy, ruleName)`. `dnsName`, `localData`, and
97 * `behavior` update in place. Rules have no labels; `list` / nuke
98 * discover them by enumerating response policies stamped with
99 * `alchemy-*` labels.
100 *
101 * ### Creating a Rule
102 * **Example:** Local A record override
103 * ```typescript
104 * const policy = yield* GCP.DNS.ResponsePolicy("Overrides", {
105 * networks: ["app-vpc"],
106 * });
107 * const rule = yield* GCP.DNS.ResponsePolicyRule("Internal", {
108 * responsePolicy: policy.responsePolicyName,
109 * dnsName: "app.internal.example.com.",
110 * localData: [{ type: "A", ttl: 300, rrdatas: ["10.0.0.10"] }],
111 * });
112 * ```
113 *
114 * **Example:** Bypass the response policy for a name
115 * ```typescript
116 * const passthrough = yield* GCP.DNS.ResponsePolicyRule("Passthrough", {
117 * responsePolicy: policy.responsePolicyName,
118 * dnsName: "cdn.example.com.",
119 * behavior: "bypassResponsePolicy",
120 * });
121 * ```
122 *
123 * @resource
124 * @category DNS
125 */
126 export const ResponsePolicyRule = Resource<ResponsePolicyRule>("GCP.DNS.ResponsePolicyRule");
127
128 export class ResponsePolicyRuleNotResolved extends Data.TaggedError(
129 "GCP.DNS.ResponsePolicyRuleNotResolved",
130 )<{
131 responsePolicy: string;
132 ruleName: string;
133 }> {}
134
135 export class ResponsePolicyRulePolicyNotFound extends Data.TaggedError(
136 "GCP.DNS.ResponsePolicyRulePolicyNotFound",
137 )<{
138 responsePolicy: string;
139 }> {}
140
141 const withTrailingDot = (name: string) => (name.endsWith(".") ? name : `${name}.`);
142
143 const normalizeFqdn = (name: string) => withTrailingDot(name).toLowerCase();
144
145 const toRuleName = (id: string, name: string | undefined, existing?: string) =>
146 Effect.gen(function* () {
147 if (name !== undefined) return name;
148 if (existing !== undefined) return existing;
149 const generated = yield* createPhysicalName({
150 id,
151 maxLength: MAX_NAME_LENGTH,
152 lowercase: true,
153 });
154 const rfc = generated
155 .replace(/[^a-z0-9-]/g, "-")
156 .replace(/^[^a-z]+/, "r")
157 .slice(0, MAX_NAME_LENGTH)
158 .replace(/-+$/g, "");
159 return rfc.length > 0 ? rfc : "r";
160 });
161
162 const toLocalData = (
163 dnsName: string,
164 records: ResponsePolicyRuleLocalData[] | undefined,
165 ): ResponsePolicyRuleLocalData[] =>
166 (records ?? []).map((record) => ({
167 name: normalizeFqdn(record.name ?? dnsName),
168 type: record.type.toUpperCase(),
169 ttl: record.ttl ?? DEFAULT_TTL,
170 rrdatas: record.rrdatas ?? [],
171 }));
172
173 const observedLocalData = (rule: dns.ResponsePolicyRule): ResponsePolicyRuleLocalData[] =>
174 (rule.localData?.localDatas ?? []).map((record) => ({
175 name: record.name ? normalizeFqdn(record.name) : "",
176 type: (record.type ?? "").toUpperCase(),
177 ttl: record.ttl ?? DEFAULT_TTL,
178 rrdatas: record.rrdatas ?? [],
179 }));
180
181 const sameLocalData = (left: ResponsePolicyRuleLocalData[], right: ResponsePolicyRuleLocalData[]) =>
182 JSON.stringify(left) === JSON.stringify(right);
183
184 const toBody = (props: {
185 ruleName: string;
186 dnsName: string;
187 localData: ResponsePolicyRuleLocalData[];
188 behavior: string | undefined;
189 }): dns.ResponsePolicyRule => {
190 const body: dns.ResponsePolicyRule = {
191 ruleName: props.ruleName,
192 dnsName: props.dnsName,
193 };
194 if (props.localData.length > 0) {
195 body.localData = {
196 localDatas: props.localData.map((record) => ({
197 name: record.name,
198 type: record.type,
199 ttl: record.ttl,
200 rrdatas: record.rrdatas,
201 })),
202 };
203 } else if (props.behavior !== undefined) {
204 body.behavior = props.behavior;
205 }
206 return body;
207 };
208
209 const toAttrs = (rule: dns.ResponsePolicyRule, project: string, responsePolicy: string) => ({
210 project,
211 responsePolicy,
212 ruleName: rule.ruleName ?? "",
213 dnsName: rule.dnsName ? normalizeFqdn(rule.dnsName) : "",
214 localData: observedLocalData(rule),
215 behavior: rule.behavior,
216 kind: rule.kind,
217 });
218
219 const getPolicy = (project: string, responsePolicy: string) =>
220 dns
221 .getResponsePolicies({ project, responsePolicy })
222 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
223
224 const getByName = (project: string, responsePolicy: string, ruleName: string) =>
225 dns
226 .getResponsePolicyRules({
227 project,
228 responsePolicy,
229 responsePolicyRule: ruleName,
230 })
231 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
232
233 const listRules = (project: string, responsePolicy: string) =>
234 Effect.gen(function* () {
235 const found: dns.ResponsePolicyRule[] = [];
236 let pageToken: string | undefined;
237 for (let page = 0; page < 10; page++) {
238 const response = yield* dns.listResponsePolicyRules({
239 project,
240 responsePolicy,
241 maxResults: 1000,
242 pageToken,
243 });
244 found.push(...(response.responsePolicyRules ?? []));
245 pageToken = response.nextPageToken;
246 if (pageToken === undefined || pageToken === "") break;
247 }
248 return found;
249 }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as dns.ResponsePolicyRule[])));
250
251 const listAlchemyResponsePolicies = (project: string) =>
252 Effect.gen(function* () {
253 const found: dns.ResponsePolicy[] = [];
254 let pageToken: string | undefined;
255 for (let page = 0; page < 10; page++) {
256 const response = yield* dns.listResponsePolicies({
257 project,
258 maxResults: 1000,
259 pageToken,
260 });
261 for (const policy of response.responsePolicies ?? []) {
262 if (Object.keys(policy.labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX))) {
263 found.push(policy);
264 }
265 }
266 pageToken = response.nextPageToken;
267 if (pageToken === undefined || pageToken === "") break;
268 }
269 return found;
270 });
271
272 export const ResponsePolicyRuleProvider = () =>
273 Provider.succeed(ResponsePolicyRule, {
274 stables: ["project", "responsePolicy", "ruleName"],
275
276 diff: Effect.fn(function* ({ news, olds, output }) {
277 if (!isResolved(news)) return undefined;
278 const previousPolicy = olds?.responsePolicy ?? output?.responsePolicy;
279 const previousName = olds?.ruleName ?? output?.ruleName;
280 const nextName = news.ruleName ?? previousName;
281 const policyChanged = previousPolicy !== undefined && news.responsePolicy !== previousPolicy;
282 const nameChanged =
283 previousName !== undefined && nextName !== undefined && nextName !== previousName;
284 if (!policyChanged && !nameChanged) return undefined;
285 return { action: "replace" as const, deleteFirst: false };
286 }),
287
288 read: Effect.fn(function* ({ id, olds, output }) {
289 const env = yield* GcpEnvironment.current;
290 const responsePolicy = output?.responsePolicy ?? olds?.responsePolicy;
291 if (responsePolicy === undefined) return undefined;
292 const ruleName = yield* toRuleName(id, olds?.ruleName, output?.ruleName);
293 const existing = yield* getByName(env.project, responsePolicy, ruleName);
294 if (existing === undefined) return undefined;
295 // Rules have no labels. Identity (policy + rule name) is
296 // ownership — same as Cloud DNS record sets.
297 return toAttrs(existing, env.project, responsePolicy);
298 }),
299
300 list: () =>
301 Effect.gen(function* () {
302 const env = yield* GcpEnvironment.current;
303 const policies = yield* listAlchemyResponsePolicies(env.project);
304 const pages = yield* Effect.forEach(
305 policies,
306 (policy) =>
307 policy.responsePolicyName
308 ? listRules(env.project, policy.responsePolicyName).pipe(
309 Effect.map((rules) =>
310 rules.map((rule) =>
311 toAttrs(rule, env.project, policy.responsePolicyName ?? ""),
312 ),
313 ),
314 )
315 : Effect.succeed([] as ReturnType<typeof toAttrs>[]),
316 { concurrency: 4 },
317 );
318 return pages.flat();
319 }),
320
321 reconcile: Effect.fn(function* ({ id, news, output }) {
322 const env = yield* GcpEnvironment.current;
323 const policy = yield* getPolicy(env.project, news.responsePolicy);
324 if (policy === undefined || policy.responsePolicyName === undefined) {
325 return yield* new ResponsePolicyRulePolicyNotFound({
326 responsePolicy: news.responsePolicy,
327 });
328 }
329 const responsePolicy = policy.responsePolicyName;
330 const ruleName = yield* toRuleName(id, news.ruleName, output?.ruleName);
331 const dnsName = normalizeFqdn(news.dnsName);
332 const localData = toLocalData(dnsName, news.localData);
333 const behavior = localData.length > 0 ? undefined : news.behavior;
334 const desired = toBody({
335 ruleName,
336 dnsName,
337 localData,
338 behavior,
339 });
340
341 let current = yield* getByName(env.project, responsePolicy, ruleName);
342
343 if (current === undefined) {
344 const created = yield* dns
345 .createResponsePolicyRules({
346 project: env.project,
347 responsePolicy,
348 body: desired,
349 })
350 .pipe(
351 Effect.catchTag("Conflict", () => getByName(env.project, responsePolicy, ruleName)),
352 );
353 current = created ?? undefined;
354 }
355
356 if (current === undefined) {
357 return yield* new ResponsePolicyRuleNotResolved({
358 responsePolicy,
359 ruleName,
360 });
361 }
362
363 const dnsChanged = normalizeFqdn(current.dnsName ?? "") !== dnsName;
364 const localChanged = !sameLocalData(observedLocalData(current), localData);
365 const behaviorChanged = (current.behavior ?? undefined) !== behavior;
366
367 if (dnsChanged || localChanged || behaviorChanged) {
368 const patched = yield* dns.patchResponsePolicyRules({
369 project: env.project,
370 responsePolicy,
371 responsePolicyRule: ruleName,
372 body: desired,
373 });
374 current =
375 patched.responsePolicyRule ??
376 (yield* getByName(env.project, responsePolicy, ruleName)) ??
377 current;
378 }
379
380 return toAttrs(current, env.project, responsePolicy);
381 }),
382
383 delete: Effect.fn(function* ({ output }) {
384 yield* dns
385 .deleteResponsePolicyRules({
386 project: output.project,
387 responsePolicy: output.responsePolicy,
388 responsePolicyRule: output.ruleName,
389 })
390 .pipe(Effect.catchTag("NotFound", () => Effect.void));
391 }),
392 });