The best way to control Claude Code, Codex and more from any computer or phone

main
ts 353 lines 11.8 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 { tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 deployedConfig,
14 encodeDescription,
15 environmentIdOf,
16 environmentNameOf,
17 hasOwnershipMarker,
18 lastSegment,
19 listProjectEnvironments,
20 missingToUndefined,
21 namesFromConfig,
22 organizationIdOf,
23 ownedById,
24 parseDescription,
25 parseOrgEnv,
26 sameText,
27 toResourceId,
28 } from "./common.ts";
29
30 const MAX_NAME_LENGTH = 255;
31
32 export type TargetServerTlsCommonName = {
33 /** TLS common name to match. */
34 value?: string;
35 /** Match the cert as a wildcard. */
36 wildcardMatch?: boolean;
37 };
38
39 export type TargetServerTlsInfo = {
40 /** Enable TLS. */
41 enabled?: boolean;
42 /** Ignore TLS certificate errors. */
43 ignoreValidationErrors?: boolean;
44 /** Enable two-way TLS. */
45 clientAuthEnabled?: boolean;
46 /** Truststore resource id. */
47 trustStore?: string;
48 /** Key alias when client auth is enabled. */
49 keyAlias?: string;
50 /** Keystore resource id when client auth is enabled. */
51 keyStore?: string;
52 /** TLS common name. */
53 commonName?: TargetServerTlsCommonName;
54 /** TLS protocol versions. */
55 protocols?: string[];
56 /** Cipher suites. */
57 ciphers?: string[];
58 /** Strictly enforce TLS. */
59 enforce?: boolean;
60 };
61
62 export type EnvironmentsTargetserverProps = {
63 /**
64 * Apigee organization id or `organizations/{org}`. Defaults to the
65 * current GCP project id. Immutable — changing it replaces the server.
66 */
67 organization?: string;
68 /**
69 * Environment id or `organizations/{org}/environments/{env}`. Immutable —
70 * changing it replaces the server.
71 */
72 environment: string;
73 /**
74 * Target server id. If omitted, a unique name is generated from the
75 * stack, stage, and logical id. Immutable — changing it replaces the
76 * server.
77 */
78 targetserverId?: string;
79 /**
80 * Hostname this target connects to (RFC-1123).
81 */
82 host: string;
83 /**
84 * Port on `host`. Must be between 1 and 65535.
85 */
86 port: number;
87 /**
88 * Protocol. Immutable — changing it replaces the server.
89 */
90 protocol?: apigee.GoogleCloudApigeeV1TargetServerProtocolEnum | (string & {});
91 /**
92 * Human-readable description. Alchemy stamps ownership into a
93 * `[alchemy …]` prefix because target servers have no labels field.
94 */
95 description?: string;
96 /**
97 * Whether the target is in rotation.
98 * @default true
99 */
100 isEnabled?: boolean;
101 /**
102 * TLS configuration (`sSLInfo` on the wire).
103 */
104 sSLInfo?: TargetServerTlsInfo;
105 };
106
107 export type EnvironmentsTargetserver = Resource<
108 "GCP.Apigee.EnvironmentsTargetserver",
109 EnvironmentsTargetserverProps,
110 {
111 /** Full resource name `organizations/{org}/environments/{env}/targetservers/{id}`. */
112 name: string;
113 /** Target server id. */
114 targetserverId: string;
115 /** Apigee organization id. */
116 organizationId: string;
117 /** Environment id. */
118 environmentId: string;
119 /** Hostname. */
120 host: string;
121 /** Port. */
122 port: number;
123 /** Protocol. */
124 protocol: string | undefined;
125 /** User description with the Alchemy ownership prefix stripped. */
126 description: string | undefined;
127 /** Whether the target is enabled. */
128 isEnabled: boolean;
129 /** TLS configuration. */
130 sSLInfo: TargetServerTlsInfo | undefined;
131 },
132 never,
133 Providers
134 >;
135
136 /**
137 * An Apigee environment TargetServer — a named backend host:port used by
138 * proxy TargetEndpoints.
139 *
140 * Target servers have no labels, so Alchemy stamps ownership into
141 * `description` for `list` / nuke. Name and protocol are identity; host,
142 * port, enabled flag, description, and TLS settings update in place.
143 *
144 * ### Creating a Target Server
145 * **Example:** HTTP backend
146 * ```typescript
147 * const backend = yield* GCP.Apigee.EnvironmentsTargetserver("Api", {
148 * environment: "eval",
149 * host: "backend.example.com",
150 * port: 443,
151 * protocol: "HTTP",
152 * sSLInfo: { enabled: true },
153 * });
154 * ```
155 *
156 * @resource
157 * @category Apigee
158 */
159 export const EnvironmentsTargetserver = Resource<EnvironmentsTargetserver>(
160 "GCP.Apigee.EnvironmentsTargetserver",
161 );
162
163 export class EnvironmentsTargetserverNotResolved extends Data.TaggedError(
164 "GCP.Apigee.EnvironmentsTargetserverNotResolved",
165 )<{
166 resourceName: string;
167 }> {}
168
169 const resourceName = (organizationId: string, environmentId: string, targetserverId: string) =>
170 `${environmentNameOf(organizationId, environmentId)}/targetservers/${targetserverId}`;
171
172 const tlsOf = (
173 info: apigee.GoogleCloudApigeeV1TlsInfo | undefined,
174 ): TargetServerTlsInfo | undefined => {
175 if (info === undefined) return undefined;
176 return {
177 enabled: info.enabled,
178 ignoreValidationErrors: info.ignoreValidationErrors,
179 clientAuthEnabled: info.clientAuthEnabled,
180 trustStore: info.trustStore,
181 keyAlias: info.keyAlias,
182 keyStore: info.keyStore,
183 commonName: info.commonName
184 ? {
185 value: info.commonName.value,
186 wildcardMatch: info.commonName.wildcardMatch,
187 }
188 : undefined,
189 protocols: info.protocols,
190 ciphers: info.ciphers,
191 enforce: info.enforce,
192 };
193 };
194
195 const toAttrs = (
196 server: apigee.GoogleCloudApigeeV1TargetServer,
197 organizationId: string,
198 environmentId: string,
199 ) => {
200 const raw = server.name ?? "";
201 const parsed = parseOrgEnv(raw);
202 const targetserverId = lastSegment(raw);
203 const description = parseDescription(server.description);
204 return {
205 name: raw.includes("/")
206 ? raw
207 : resourceName(organizationId, environmentId, targetserverId || raw),
208 targetserverId: targetserverId || raw,
209 organizationId: parsed.organizationId || organizationId,
210 environmentId: parsed.environmentId || environmentId,
211 host: server.host ?? "",
212 port: server.port ?? 0,
213 protocol: server.protocol,
214 description: description.description,
215 isEnabled: server.isEnabled !== false,
216 sSLInfo: tlsOf(server.sSLInfo),
217 };
218 };
219
220 const getByName = (name: string) =>
221 missingToUndefined(apigee.getOrganizationsEnvironmentsTargetservers({ name }));
222
223 const jsonOf = (value: unknown) => JSON.stringify(value ?? null);
224
225 export const EnvironmentsTargetserverProvider = () =>
226 Provider.succeed(EnvironmentsTargetserver, {
227 stables: ["name", "targetserverId", "organizationId", "environmentId"],
228
229 diff: Effect.fn(function* ({ news, olds, output }) {
230 if (!isResolved(news)) return undefined;
231 const previousId = olds?.targetserverId ?? output?.targetserverId;
232 const previousOrg = olds?.organization ?? output?.organizationId;
233 const previousEnv = olds?.environment ?? output?.environmentId;
234 const previousProtocol = olds?.protocol ?? output?.protocol;
235 const idChanged =
236 previousId !== undefined &&
237 news.targetserverId !== undefined &&
238 news.targetserverId !== previousId;
239 const orgChanged =
240 previousOrg !== undefined &&
241 news.organization !== undefined &&
242 organizationIdOf(news.organization, "") !== organizationIdOf(previousOrg, "");
243 const envChanged =
244 previousEnv !== undefined &&
245 environmentIdOf(news.environment) !== environmentIdOf(previousEnv);
246 const protocolChanged =
247 previousProtocol !== undefined &&
248 news.protocol !== undefined &&
249 news.protocol !== previousProtocol;
250 if (idChanged || orgChanged || envChanged || protocolChanged) {
251 return { action: "replace" as const, deleteFirst: false };
252 }
253 return undefined;
254 }),
255
256 read: Effect.fn(function* ({ id, olds, output }) {
257 const { project } = yield* GcpEnvironment.current;
258 const organizationId = organizationIdOf(
259 olds?.organization ?? output?.organizationId,
260 project,
261 );
262 const environmentId = environmentIdOf(olds?.environment ?? output?.environmentId ?? "");
263 const targetserverId = yield* toResourceId(id, olds?.targetserverId, output?.targetserverId, {
264 maxLength: MAX_NAME_LENGTH,
265 });
266 const name = output?.name ?? resourceName(organizationId, environmentId, targetserverId);
267 const existing = yield* getByName(name);
268 if (existing === undefined) return undefined;
269 const attrs = toAttrs(existing, organizationId, environmentId);
270 const { labels } = parseDescription(existing.description);
271 return (yield* ownedById(id, tagRecord(labels))) ? attrs : Unowned(attrs);
272 }),
273
274 list: () =>
275 Effect.gen(function* () {
276 const environments = yield* listProjectEnvironments();
277 const found: EnvironmentsTargetserver["Attributes"][] = [];
278 for (const item of environments) {
279 const ids = namesFromConfig((yield* deployedConfig(item.parent))?.targets);
280 for (const raw of ids) {
281 const name = raw.includes("/")
282 ? raw
283 : resourceName(item.organizationId, item.environmentId, raw);
284 const server = yield* getByName(name);
285 if (server === undefined) continue;
286 if (!hasOwnershipMarker(server.description)) continue;
287 found.push(toAttrs(server, item.organizationId, item.environmentId));
288 }
289 }
290 return found;
291 }),
292
293 reconcile: Effect.fn(function* ({ id, news, output }) {
294 const { project } = yield* GcpEnvironment.current;
295 const organizationId = organizationIdOf(news.organization, project);
296 const environmentId = environmentIdOf(news.environment);
297 const targetserverId = yield* toResourceId(id, news.targetserverId, output?.targetserverId, {
298 maxLength: MAX_NAME_LENGTH,
299 });
300 const parent = environmentNameOf(organizationId, environmentId);
301 const name = resourceName(organizationId, environmentId, targetserverId);
302 const ownership = yield* createInternalLabels(id);
303 const desiredDescription = encodeDescription(ownership, news.description);
304 const desiredEnabled = news.isEnabled !== false;
305 const body: apigee.GoogleCloudApigeeV1TargetServer = {
306 name: targetserverId,
307 host: news.host,
308 port: news.port,
309 protocol: news.protocol,
310 description: desiredDescription,
311 isEnabled: desiredEnabled,
312 sSLInfo: news.sSLInfo,
313 };
314
315 let current = yield* getByName(output?.name ?? name);
316
317 if (current === undefined) {
318 const created = yield* apigee
319 .createOrganizationsEnvironmentsTargetservers({
320 parent,
321 name: targetserverId,
322 body,
323 })
324 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
325 current = created ?? undefined;
326 }
327
328 if (current === undefined) {
329 return yield* new EnvironmentsTargetserverNotResolved({ resourceName: name });
330 }
331
332 const hostChanged = !sameText(current.host, news.host);
333 const portChanged = (current.port ?? 0) !== news.port;
334 const descriptionChanged = !sameText(current.description, desiredDescription);
335 const enabledChanged = (current.isEnabled !== false) !== desiredEnabled;
336 const tlsChanged = jsonOf(tlsOf(current.sSLInfo)) !== jsonOf(news.sSLInfo);
337
338 if (hostChanged || portChanged || descriptionChanged || enabledChanged || tlsChanged) {
339 current = yield* apigee.updateOrganizationsEnvironmentsTargetservers({
340 name,
341 body,
342 });
343 }
344
345 return toAttrs(current, organizationId, environmentId);
346 }),
347
348 delete: Effect.fn(function* ({ output }) {
349 yield* apigee
350 .deleteOrganizationsEnvironmentsTargetservers({ name: output.name })
351 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
352 }),
353 });