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

main
ts 269 lines 9.31 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 const DEFAULT_RESOURCE_TYPE = "KeyStore";
32
33 export type EnvironmentsReferenceProps = {
34 /**
35 * Apigee organization id or `organizations/{org}`. Defaults to the
36 * current GCP project id. Immutable — changing it replaces the reference.
37 */
38 organization?: string;
39 /**
40 * Environment id or `organizations/{org}/environments/{env}`. Immutable —
41 * changing it replaces the reference.
42 */
43 environment: string;
44 /**
45 * Reference id. If omitted, a unique name is generated from the stack,
46 * stage, and logical id. Immutable — changing it replaces the reference.
47 */
48 referenceId?: string;
49 /**
50 * Id of the keystore or truststore this reference points at. Must exist
51 * in the same environment.
52 */
53 refers: string;
54 /**
55 * Resource type referred to. Valid values are `KeyStore` or `TrustStore`.
56 * @default "KeyStore"
57 */
58 resourceType?: string;
59 /**
60 * Human-readable description. Alchemy stamps ownership into a
61 * `[alchemy …]` prefix because references have no labels field.
62 */
63 description?: string;
64 };
65
66 export type EnvironmentsReference = Resource<
67 "GCP.Apigee.EnvironmentsReference",
68 EnvironmentsReferenceProps,
69 {
70 /** Full resource name `organizations/{org}/environments/{env}/references/{ref}`. */
71 name: string;
72 /** Reference id. */
73 referenceId: string;
74 /** Apigee organization id. */
75 organizationId: string;
76 /** Environment id. */
77 environmentId: string;
78 /** Id of the referred keystore or truststore. */
79 refers: string;
80 /** Resource type (`KeyStore` or `TrustStore`). */
81 resourceType: string | undefined;
82 /** User description with the Alchemy ownership prefix stripped. */
83 description: string | undefined;
84 },
85 never,
86 Providers
87 >;
88
89 /**
90 * An Apigee environment reference to a keystore or truststore.
91 *
92 * References have no labels, so Alchemy stamps ownership into
93 * `description` for `list` / nuke. Name is identity; `refers`,
94 * `resourceType`, and description update in place.
95 *
96 * ### Creating a Reference
97 * **Example:** Point at a keystore
98 * ```typescript
99 * const keystore = yield* GCP.Apigee.EnvironmentsKeystore("Tls", {
100 * environment: "eval",
101 * });
102 * const reference = yield* GCP.Apigee.EnvironmentsReference("TlsRef", {
103 * environment: "eval",
104 * refers: keystore.keystoreId,
105 * resourceType: "KeyStore",
106 * });
107 * ```
108 *
109 * @resource
110 * @category Apigee
111 */
112 export const EnvironmentsReference = Resource<EnvironmentsReference>(
113 "GCP.Apigee.EnvironmentsReference",
114 );
115
116 export class EnvironmentsReferenceNotResolved extends Data.TaggedError(
117 "GCP.Apigee.EnvironmentsReferenceNotResolved",
118 )<{
119 resourceName: string;
120 }> {}
121
122 const resourceName = (organizationId: string, environmentId: string, referenceId: string) =>
123 `${environmentNameOf(organizationId, environmentId)}/references/${referenceId}`;
124
125 const toAttrs = (
126 reference: apigee.GoogleCloudApigeeV1Reference,
127 organizationId: string,
128 environmentId: string,
129 ) => {
130 const raw = reference.name ?? "";
131 const parsed = parseOrgEnv(raw);
132 const referenceId = lastSegment(raw);
133 const description = parseDescription(reference.description);
134 return {
135 name: raw.includes("/") ? raw : resourceName(organizationId, environmentId, referenceId || raw),
136 referenceId: referenceId || raw,
137 organizationId: parsed.organizationId || organizationId,
138 environmentId: parsed.environmentId || environmentId,
139 refers: reference.refers ?? "",
140 resourceType: reference.resourceType,
141 description: description.description,
142 };
143 };
144
145 const getByName = (name: string) =>
146 missingToUndefined(apigee.getOrganizationsEnvironmentsReferences({ name }));
147
148 export const EnvironmentsReferenceProvider = () =>
149 Provider.succeed(EnvironmentsReference, {
150 stables: ["name", "referenceId", "organizationId", "environmentId"],
151
152 diff: Effect.fn(function* ({ news, olds, output }) {
153 if (!isResolved(news)) return undefined;
154 const previousId = olds?.referenceId ?? output?.referenceId;
155 const previousOrg = olds?.organization ?? output?.organizationId;
156 const previousEnv = olds?.environment ?? output?.environmentId;
157 const idChanged =
158 previousId !== undefined &&
159 news.referenceId !== undefined &&
160 news.referenceId !== previousId;
161 const orgChanged =
162 previousOrg !== undefined &&
163 news.organization !== undefined &&
164 organizationIdOf(news.organization, "") !== organizationIdOf(previousOrg, "");
165 const envChanged =
166 previousEnv !== undefined &&
167 environmentIdOf(news.environment) !== environmentIdOf(previousEnv);
168 if (idChanged || orgChanged || envChanged) {
169 return { action: "replace" as const, deleteFirst: false };
170 }
171 return undefined;
172 }),
173
174 read: Effect.fn(function* ({ id, olds, output }) {
175 const { project } = yield* GcpEnvironment.current;
176 const organizationId = organizationIdOf(
177 olds?.organization ?? output?.organizationId,
178 project,
179 );
180 const environmentId = environmentIdOf(olds?.environment ?? output?.environmentId ?? "");
181 const referenceId = yield* toResourceId(id, olds?.referenceId, output?.referenceId, {
182 maxLength: MAX_NAME_LENGTH,
183 });
184 const name = output?.name ?? resourceName(organizationId, environmentId, referenceId);
185 const existing = yield* getByName(name);
186 if (existing === undefined) return undefined;
187 const attrs = toAttrs(existing, organizationId, environmentId);
188 const { labels } = parseDescription(existing.description);
189 return (yield* ownedById(id, tagRecord(labels))) ? attrs : Unowned(attrs);
190 }),
191
192 list: () =>
193 Effect.gen(function* () {
194 const environments = yield* listProjectEnvironments();
195 const found: EnvironmentsReference["Attributes"][] = [];
196 for (const item of environments) {
197 const ids = namesFromConfig((yield* deployedConfig(item.parent))?.resourceReferences);
198 for (const raw of ids) {
199 const name = raw.includes("/")
200 ? raw
201 : resourceName(item.organizationId, item.environmentId, raw);
202 const reference = yield* getByName(name);
203 if (reference === undefined) continue;
204 if (!hasOwnershipMarker(reference.description)) continue;
205 found.push(toAttrs(reference, item.organizationId, item.environmentId));
206 }
207 }
208 return found;
209 }),
210
211 reconcile: Effect.fn(function* ({ id, news, output }) {
212 const { project } = yield* GcpEnvironment.current;
213 const organizationId = organizationIdOf(news.organization, project);
214 const environmentId = environmentIdOf(news.environment);
215 const referenceId = yield* toResourceId(id, news.referenceId, output?.referenceId, {
216 maxLength: MAX_NAME_LENGTH,
217 });
218 const parent = environmentNameOf(organizationId, environmentId);
219 const name = resourceName(organizationId, environmentId, referenceId);
220 const ownership = yield* createInternalLabels(id);
221 const desiredDescription = encodeDescription(ownership, news.description);
222 const desiredType = news.resourceType ?? DEFAULT_RESOURCE_TYPE;
223
224 let current = yield* getByName(output?.name ?? name);
225
226 if (current === undefined) {
227 const created = yield* apigee
228 .createOrganizationsEnvironmentsReferences({
229 parent,
230 body: {
231 name: referenceId,
232 refers: news.refers,
233 resourceType: desiredType,
234 description: desiredDescription,
235 },
236 })
237 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
238 current = created ?? undefined;
239 }
240
241 if (current === undefined) {
242 return yield* new EnvironmentsReferenceNotResolved({ resourceName: name });
243 }
244
245 if (
246 !sameText(current.refers, news.refers) ||
247 !sameText(current.resourceType, desiredType) ||
248 !sameText(current.description, desiredDescription)
249 ) {
250 current = yield* apigee.updateOrganizationsEnvironmentsReferences({
251 name,
252 body: {
253 name: referenceId,
254 refers: news.refers,
255 resourceType: desiredType,
256 description: desiredDescription,
257 },
258 });
259 }
260
261 return toAttrs(current, organizationId, environmentId);
262 }),
263
264 delete: Effect.fn(function* ({ output }) {
265 yield* apigee
266 .deleteOrganizationsEnvironmentsReferences({ name: output.name })
267 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
268 }),
269 });