@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 432 lines 14.9 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_GLOBAL,
14 changedFields,
15 collectPages,
16 hasAlchemyLabelKeys,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 resourceName,
21 rfc1035,
22 sameJson,
23 sameStringList,
24 toPhysicalId,
25 userLabels,
26 waitForOperation,
27 waitUntilGone,
28 waitUntilPresent,
29 } from "./internal.ts";
30
31 const COLLECTION = "endpointPolicies";
32 const DEFAULT_TYPE = "SIDECAR_PROXY";
33
34 export type EndpointPolicyType = networkservices.EndpointPolicyTypeEnum | (string & {});
35
36 export type EndpointPolicyMetadataLabel = {
37 /** Label name presented as a key in xDS node metadata. */
38 labelName?: string;
39 /** Label value presented as the matching value. */
40 labelValue?: string;
41 };
42
43 export type EndpointPolicyMetadataLabelMatcher = {
44 /**
45 * How labels are combined. `MATCH_ANY` matches if any listed label is
46 * present; `MATCH_ALL` requires every listed label.
47 */
48 metadataLabelMatchCriteria?: string;
49 /**
50 * Label pairs that must match xDS node metadata. At most 64 entries.
51 * Empty with `MATCH_ANY` is a wildcard.
52 */
53 metadataLabels?: EndpointPolicyMetadataLabel[];
54 };
55
56 export type EndpointPolicyEndpointMatcher = {
57 /** Matcher based on xDS client node metadata. */
58 metadataLabelMatcher?: EndpointPolicyMetadataLabelMatcher;
59 };
60
61 export type EndpointPolicyTrafficPortSelector = {
62 /**
63 * Ports, ranges (`80-90`), named ports, or `*` for all ports. Empty
64 * selects every port.
65 */
66 ports?: string[];
67 };
68
69 export type EndpointPolicyProps = {
70 /**
71 * EndpointPolicy id (the `{endpointPolicy}` segment of
72 * `projects/{project}/locations/{location}/endpointPolicies/{endpointPolicy}`).
73 * If omitted, a unique name is generated from the stack, stage, and
74 * logical id. Must be 1-63 characters and not start with a number.
75 * Immutable — changing it replaces the policy.
76 */
77 endpointPolicyId?: string;
78 /**
79 * Location (`global`, `us-central1`, …). Immutable — changing it
80 * replaces the policy. `US-CENTRAL1` is accepted and normalized to
81 * `us-central1`.
82 * @default "global"
83 */
84 location?: string;
85 /**
86 * Endpoint policy type. Used to validate configuration.
87 * @default "SIDECAR_PROXY"
88 */
89 type?: EndpointPolicyType;
90 /**
91 * Matcher that selects endpoints this policy applies to.
92 */
93 endpointMatcher?: EndpointPolicyEndpointMatcher;
94 /**
95 * Port selector for matched endpoints. Omitted applies to every port.
96 */
97 trafficPortSelector?: EndpointPolicyTrafficPortSelector;
98 /**
99 * AuthorizationPolicy resource URL applied to inbound traffic. Empty
100 * disables authorization.
101 */
102 authorizationPolicy?: string;
103 /**
104 * ServerTlsPolicy URL used to terminate inbound TLS. Empty leaves the
105 * endpoint open.
106 */
107 serverTlsPolicy?: string;
108 /**
109 * ClientTlsPolicy URL applied to traffic from the sidecar proxy to the
110 * backend. Applicable only when `type` is `SIDECAR_PROXY`.
111 */
112 clientTlsPolicy?: string;
113 /**
114 * Human-readable description. Max length 1024 characters.
115 */
116 description?: string;
117 /**
118 * User labels. Alchemy ownership labels are merged in automatically.
119 */
120 labels?: Record<string, string>;
121 };
122
123 export type EndpointPolicy = Resource<
124 "GCP.NetworkServices.EndpointPolicy",
125 EndpointPolicyProps,
126 {
127 /** Full resource name `projects/{project}/locations/{location}/endpointPolicies/{endpointPolicy}`. */
128 name: string;
129 /** EndpointPolicy id (last path segment). */
130 endpointPolicyId: string;
131 /** Project id. */
132 project: string;
133 /** Location id (`global`, `us-central1`, …). */
134 location: string;
135 /** Endpoint policy type. */
136 type: string;
137 /** Matcher currently configured. */
138 endpointMatcher: EndpointPolicyEndpointMatcher | undefined;
139 /** Port selector currently configured. */
140 trafficPortSelector: EndpointPolicyTrafficPortSelector | undefined;
141 /** AuthorizationPolicy URL, if set. */
142 authorizationPolicy: string | undefined;
143 /** ServerTlsPolicy URL, if set. */
144 serverTlsPolicy: string | undefined;
145 /** ClientTlsPolicy URL, if set. */
146 clientTlsPolicy: string | undefined;
147 /** User-provided description. */
148 description: string | undefined;
149 /** User labels (Alchemy ownership labels stripped). */
150 labels: Record<string, string>;
151 /** RFC3339 creation timestamp. */
152 createTime: string | undefined;
153 /** RFC3339 last-update timestamp. */
154 updateTime: string | undefined;
155 },
156 never,
157 Providers
158 >;
159
160 /**
161 * A Network Services EndpointPolicy — applies TLS and authorization
162 * configuration to Traffic Director endpoints that match a metadata
163 * selector.
164 *
165 * Changing `endpointPolicyId`, `location`, or `type` replaces the
166 * policy. Description, labels, matcher, port selector, and policy URLs
167 * update in place.
168 *
169 * ### Creating an EndpointPolicy
170 * **Example:** Sidecar proxy with a metadata matcher
171 * ```typescript
172 * const policy = yield* GCP.NetworkServices.EndpointPolicy("Sidecar", {
173 * type: "SIDECAR_PROXY",
174 * endpointMatcher: {
175 * metadataLabelMatcher: {
176 * metadataLabelMatchCriteria: "MATCH_ANY",
177 * metadataLabels: [{ labelName: "app", labelValue: "web" }],
178 * },
179 * },
180 * });
181 * ```
182 *
183 * **Example:** Named policy with a port selector
184 * ```typescript
185 * const policy = yield* GCP.NetworkServices.EndpointPolicy("Sidecar", {
186 * endpointPolicyId: "app-sidecar",
187 * description: "prod sidecars",
188 * labels: { env: "prod" },
189 * type: "SIDECAR_PROXY",
190 * trafficPortSelector: { ports: ["8080"] },
191 * endpointMatcher: {
192 * metadataLabelMatcher: {
193 * metadataLabelMatchCriteria: "MATCH_ANY",
194 * metadataLabels: [{ labelName: "app", labelValue: "web" }],
195 * },
196 * },
197 * });
198 * ```
199 *
200 * @resource
201 * @category NetworkServices
202 */
203 export const EndpointPolicy = Resource<EndpointPolicy>("GCP.NetworkServices.EndpointPolicy");
204
205 const toLabel = (
206 label:
207 | EndpointPolicyMetadataLabel
208 | networkservices.EndpointMatcherMetadataLabelMatcherMetadataLabels,
209 ): EndpointPolicyMetadataLabel => ({
210 labelName: label.labelName,
211 labelValue: label.labelValue,
212 });
213
214 const toMatcher = (
215 matcher: EndpointPolicyEndpointMatcher | networkservices.EndpointMatcher | undefined,
216 ): EndpointPolicyEndpointMatcher | undefined => {
217 const metadata = matcher?.metadataLabelMatcher;
218 if (metadata === undefined) return undefined;
219 return {
220 metadataLabelMatcher: {
221 metadataLabelMatchCriteria: metadata.metadataLabelMatchCriteria,
222 metadataLabels: (metadata.metadataLabels ?? []).map(toLabel),
223 },
224 };
225 };
226
227 const toPortSelector = (
228 selector: EndpointPolicyTrafficPortSelector | networkservices.TrafficPortSelector | undefined,
229 ): EndpointPolicyTrafficPortSelector | undefined => {
230 if (selector === undefined) return undefined;
231 return { ports: selector.ports ?? [] };
232 };
233
234 const toAttrs = (policy: networkservices.EndpointPolicy, project: string) => {
235 const name = policy.name ?? "";
236 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
237 return {
238 name,
239 endpointPolicyId: parsed.id,
240 project: parsed.project || project,
241 location: parsed.location || DEFAULT_GLOBAL,
242 type: policy.type ?? DEFAULT_TYPE,
243 endpointMatcher: toMatcher(policy.endpointMatcher),
244 trafficPortSelector: toPortSelector(policy.trafficPortSelector),
245 authorizationPolicy: policy.authorizationPolicy,
246 serverTlsPolicy: policy.serverTlsPolicy,
247 clientTlsPolicy: policy.clientTlsPolicy,
248 description: policy.description,
249 labels: userLabels(policy.labels),
250 createTime: policy.createTime,
251 updateTime: policy.updateTime,
252 };
253 };
254
255 const getByName = (name: string) =>
256 networkservices
257 .getProjectsLocationsEndpointPolicies({ name })
258 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
259
260 export const EndpointPolicyProvider = () =>
261 Provider.succeed(EndpointPolicy, {
262 stables: ["name", "endpointPolicyId", "project", "location", "createTime"],
263
264 diff: Effect.fn(function* ({ news, olds, output }) {
265 if (!isResolved(news)) return undefined;
266 const previousId = olds?.endpointPolicyId ?? output?.endpointPolicyId;
267 const nextId = news.endpointPolicyId
268 ? rfc1035(news.endpointPolicyId, "endpoint-policy")
269 : previousId;
270 const previousLocation = normalizeLocation(
271 olds?.location ?? output?.location,
272 DEFAULT_GLOBAL,
273 );
274 const nextLocation = normalizeLocation(
275 news.location ?? olds?.location ?? output?.location,
276 DEFAULT_GLOBAL,
277 );
278 const previousType = olds?.type ?? output?.type ?? DEFAULT_TYPE;
279 const nextType = news.type ?? previousType;
280 if (
281 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
282 previousLocation !== nextLocation ||
283 previousType !== nextType
284 ) {
285 return { action: "replace" as const };
286 }
287 return undefined;
288 }),
289
290 read: Effect.fn(function* ({ id, olds, output }) {
291 const env = yield* GcpEnvironment.current;
292 const endpointPolicyId = yield* toPhysicalId(
293 id,
294 olds?.endpointPolicyId,
295 output?.endpointPolicyId,
296 "endpoint-policy",
297 );
298 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
299 const name =
300 output?.name ?? resourceName(env.project, location, COLLECTION, endpointPolicyId);
301 const existing = yield* getByName(name);
302 if (existing === undefined) return undefined;
303 const attrs = toAttrs(existing, env.project);
304 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
305 }),
306
307 list: () =>
308 Effect.gen(function* () {
309 const env = yield* GcpEnvironment.current;
310 const items = yield* collectPages(
311 networkservices.listProjectsLocationsEndpointPolicies.pages({
312 parent: parentOf(env.project, "-"),
313 pageSize: 1000,
314 returnPartialSuccess: true,
315 }),
316 (page) => page.endpointPolicies,
317 );
318 return items
319 .filter((item) => hasAlchemyLabelKeys(item.labels))
320 .map((item) => toAttrs(item, env.project));
321 }),
322
323 reconcile: Effect.fn(function* ({ id, news, output }) {
324 const env = yield* GcpEnvironment.current;
325 const endpointPolicyId = yield* toPhysicalId(
326 id,
327 news.endpointPolicyId,
328 output?.endpointPolicyId,
329 "endpoint-policy",
330 );
331 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
332 const name = resourceName(env.project, location, COLLECTION, endpointPolicyId);
333 const desiredLabels = {
334 ...toLabels(news.labels),
335 ...(yield* createInternalLabels(id)),
336 };
337 const type = news.type ?? DEFAULT_TYPE;
338 const desiredMatcher = toMatcher(news.endpointMatcher);
339 const desiredPorts = toPortSelector(news.trafficPortSelector);
340
341 let current = yield* getByName(name);
342
343 if (current === undefined) {
344 const created = yield* networkservices
345 .createProjectsLocationsEndpointPolicies({
346 parent: parentOf(env.project, location),
347 endpointPolicyId,
348 body: {
349 type,
350 labels: desiredLabels,
351 description: news.description,
352 endpointMatcher: desiredMatcher,
353 trafficPortSelector: desiredPorts,
354 authorizationPolicy: news.authorizationPolicy,
355 serverTlsPolicy: news.serverTlsPolicy,
356 clientTlsPolicy: news.clientTlsPolicy,
357 },
358 })
359 .pipe(
360 Effect.retry({
361 while: (error) => error._tag === "Conflict",
362 times: 5,
363 schedule: Schedule.spaced("2 seconds"),
364 }),
365 Effect.catchTag("Conflict", () => Effect.undefined),
366 );
367 if (created !== undefined) {
368 yield* waitForOperation(created);
369 }
370 current = yield* waitUntilPresent(getByName(name), name);
371 }
372
373 const observedLabels = tagRecord(current.labels);
374 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
375 const labelsChanged = upsert.length > 0 || removed.length > 0;
376 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
377 const matcherChanged = !sameJson(toMatcher(current.endpointMatcher), desiredMatcher);
378 const portsChanged = !sameStringList(current.trafficPortSelector?.ports, desiredPorts?.ports);
379 const authzChanged = (current.authorizationPolicy ?? "") !== (news.authorizationPolicy ?? "");
380 const serverTlsChanged = (current.serverTlsPolicy ?? "") !== (news.serverTlsPolicy ?? "");
381 const clientTlsChanged = (current.clientTlsPolicy ?? "") !== (news.clientTlsPolicy ?? "");
382
383 const updateMask = changedFields([
384 ["labels", labelsChanged],
385 ["description", descriptionChanged],
386 ["endpointMatcher", matcherChanged],
387 ["trafficPortSelector", portsChanged],
388 ["authorizationPolicy", authzChanged],
389 ["serverTlsPolicy", serverTlsChanged],
390 ["clientTlsPolicy", clientTlsChanged],
391 ]);
392
393 if (updateMask.length > 0) {
394 const operation = yield* networkservices.patchProjectsLocationsEndpointPolicies({
395 name: current.name ?? name,
396 updateMask: updateMask.join(","),
397 body: {
398 name: current.name ?? name,
399 type,
400 labels: desiredLabels,
401 description: news.description,
402 endpointMatcher: desiredMatcher,
403 trafficPortSelector: desiredPorts,
404 authorizationPolicy: news.authorizationPolicy,
405 serverTlsPolicy: news.serverTlsPolicy,
406 clientTlsPolicy: news.clientTlsPolicy,
407 },
408 });
409 yield* waitForOperation(operation);
410 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
411 }
412
413 return toAttrs(current, env.project);
414 }),
415
416 delete: Effect.fn(function* ({ output }) {
417 const operation = yield* networkservices
418 .deleteProjectsLocationsEndpointPolicies({ name: output.name })
419 .pipe(
420 Effect.retry({
421 while: (error) => error._tag === "Conflict",
422 times: 8,
423 schedule: Schedule.spaced("2 seconds"),
424 }),
425 Effect.catchTag("NotFound", () => Effect.undefined),
426 );
427 if (operation !== undefined) {
428 yield* waitForOperation(operation, { notFoundOk: true });
429 }
430 yield* waitUntilGone(getByName(output.name), output.name);
431 }),
432 });