@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 293 lines 10.3 KB
Raw
1 import * as parametermanager from "@distilled.cloud/gcp/parametermanager_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 ParameterNotResolved,
14 deleteVersions,
15 getParameter,
16 lastSegment,
17 listAlchemyParameters,
18 normalizeFormat,
19 normalizeLocation,
20 parameterResourceName,
21 parseParameterName,
22 sameText,
23 toPhysicalId,
24 userLabels,
25 waitUntilParameterGone,
26 } from "./internal.ts";
27
28 export type ParameterFormat = parametermanager.ParameterFormatEnum | (string & {});
29
30 export type ParameterProps = {
31 /**
32 * Parameter id (the `{parameter}` segment of
33 * `projects/{project}/locations/{location}/parameters/{parameter}`).
34 * If omitted, a unique name is generated from the stack, stage, and
35 * logical id. Must be 1-63 characters, start with a letter, and match
36 * `[a-zA-Z][a-zA-Z0-9_-]*`. Immutable — changing it replaces the
37 * parameter.
38 */
39 parameterId?: string;
40 /**
41 * Parameter Manager location (`global`, `us-central1`, …). Immutable —
42 * changing it replaces the parameter. `GLOBAL` is accepted and
43 * normalized to `global`. Regional locations require Parameter Manager
44 * regional access on the project.
45 * @default "global"
46 */
47 location?: string;
48 /**
49 * Payload format. Immutable — changing it replaces the parameter. The
50 * API defaults unspecified values to `UNFORMATTED`. `JSON` and `YAML`
51 * enable secret-reference rendering on versions.
52 * @default "UNFORMATTED"
53 */
54 format?: ParameterFormat;
55 /**
56 * Cloud KMS CryptoKey used to encrypt versions
57 * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`).
58 * Must live in the same location as the parameter. Empty or omitted
59 * uses Google-managed encryption. Mutable.
60 */
61 kmsKey?: string;
62 /**
63 * User labels. Alchemy ownership labels are merged in automatically.
64 */
65 labels?: Record<string, string>;
66 };
67
68 export type Parameter = Resource<
69 "GCP.ParameterManager.Parameter",
70 ParameterProps,
71 {
72 /** Full resource name `projects/{project}/locations/{location}/parameters/{parameter}`. */
73 name: string;
74 /** Parameter id (last path segment). */
75 parameterId: string;
76 /** Project id. */
77 project: string;
78 /** Location id (`us-central1`, `global`, …). */
79 location: string;
80 /** Payload format (`UNFORMATTED`, `YAML`, `JSON`). */
81 format: string;
82 /** CMEK resource name, if set. */
83 kmsKey: string | undefined;
84 /** User labels (Alchemy ownership labels stripped). */
85 labels: Record<string, string>;
86 /** IAM policy member for the user-assigned name. */
87 iamPolicyNamePrincipal: string | undefined;
88 /** IAM policy member for the system-assigned uid. */
89 iamPolicyUidPrincipal: string | undefined;
90 /** RFC3339 creation timestamp. */
91 createTime: string | undefined;
92 /** RFC3339 last-update timestamp. */
93 updateTime: string | undefined;
94 },
95 never,
96 Providers
97 >;
98
99 /**
100 * A Parameter Manager parameter — metadata and encryption for versioned
101 * payloads. Version data lives on {@link ParametersVersion}.
102 *
103 * Changing `parameterId`, `location`, or `format` replaces the parameter.
104 * Labels and `kmsKey` update in place.
105 *
106 * ### Creating a Parameter
107 * **Example:** Generated name
108 * ```typescript
109 * const parameter = yield* GCP.ParameterManager.Parameter("AppConfig", {});
110 * ```
111 *
112 * **Example:** Explicit id, format, and labels
113 * ```typescript
114 * const parameter = yield* GCP.ParameterManager.Parameter("AppConfig", {
115 * parameterId: "order-config",
116 * format: "JSON",
117 * labels: { env: "prod" },
118 * });
119 * ```
120 *
121 * ### Parameter Versions
122 * **Example:** Store a JSON payload
123 * ```typescript
124 * const parameter = yield* GCP.ParameterManager.Parameter("AppConfig", {
125 * format: "JSON",
126 * });
127 * const version = yield* GCP.ParameterManager.ParametersVersion("V1", {
128 * parameter: parameter.name,
129 * data: JSON.stringify({ host: "api.example.com" }),
130 * });
131 * ```
132 *
133 * @resource
134 * @category ParameterManager
135 */
136 export const Parameter = Resource<Parameter>("GCP.ParameterManager.Parameter");
137
138 export { ParameterNotResolved };
139
140 const toAttrs = (parameter: parametermanager.Parameter, project: string) => {
141 const name = parameter.name ?? "";
142 const parsed = parseParameterName(name);
143 return {
144 name,
145 parameterId: parsed.parameterId,
146 project: parsed.project || project,
147 location: parsed.location,
148 format: normalizeFormat(parameter.format),
149 kmsKey: parameter.kmsKey,
150 labels: userLabels(parameter.labels),
151 iamPolicyNamePrincipal: parameter.policyMember?.iamPolicyNamePrincipal,
152 iamPolicyUidPrincipal: parameter.policyMember?.iamPolicyUidPrincipal,
153 createTime: parameter.createTime,
154 updateTime: parameter.updateTime,
155 };
156 };
157
158 export const ParameterProvider = () =>
159 Provider.succeed(Parameter, {
160 stables: ["name", "parameterId", "project", "location", "format", "createTime"],
161
162 diff: Effect.fn(function* ({ news, olds, output }) {
163 if (!isResolved(news)) return undefined;
164 const previousId = olds?.parameterId ?? output?.parameterId;
165 const nextId = news.parameterId ?? previousId;
166 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
167 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
168 const previousFormat = normalizeFormat(olds?.format ?? output?.format);
169 const nextFormat = normalizeFormat(news.format ?? olds?.format ?? output?.format);
170 const idChanged = previousId !== undefined && nextId !== undefined && previousId !== nextId;
171 const locationChanged = previousLocation !== nextLocation;
172 const formatChanged = previousFormat !== nextFormat;
173 if (!idChanged && !locationChanged && !formatChanged) return undefined;
174 return {
175 action: "replace" as const,
176 deleteFirst:
177 !idChanged &&
178 !locationChanged &&
179 formatChanged &&
180 previousId !== undefined &&
181 nextId === previousId,
182 };
183 }),
184
185 read: Effect.fn(function* ({ id, olds, output }) {
186 const env = yield* GcpEnvironment.current;
187 const parameterId = yield* toPhysicalId(
188 id,
189 olds?.parameterId,
190 output?.parameterId,
191 "parameter",
192 );
193 const location = normalizeLocation(olds?.location ?? output?.location);
194 const name = output?.name ?? parameterResourceName(env.project, location, parameterId);
195 const existing = yield* getParameter(name);
196 if (existing === undefined) return undefined;
197 const attrs = toAttrs(existing, env.project);
198 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
199 }),
200
201 list: () =>
202 Effect.gen(function* () {
203 const env = yield* GcpEnvironment.current;
204 const parameters = yield* listAlchemyParameters(env.project);
205 return parameters.map((parameter) => toAttrs(parameter, env.project));
206 }),
207
208 reconcile: Effect.fn(function* ({ id, news, output }) {
209 const env = yield* GcpEnvironment.current;
210 const parameterId = yield* toPhysicalId(
211 id,
212 news.parameterId,
213 output?.parameterId,
214 "parameter",
215 );
216 const location = normalizeLocation(news.location ?? output?.location);
217 const format = normalizeFormat(news.format ?? output?.format);
218 const name = parameterResourceName(env.project, location, parameterId);
219 const desiredLabels = {
220 ...toLabels(news.labels),
221 ...(yield* createInternalLabels(id)),
222 };
223 const desiredKmsKey = news.kmsKey ?? "";
224
225 let current = yield* getParameter(name);
226
227 if (current !== undefined && normalizeFormat(current.format) !== format) {
228 yield* deleteVersions(current.name ?? name);
229 yield* parametermanager
230 .deleteProjectsLocationsParameters({ name: current.name ?? name })
231 .pipe(Effect.catchTag("NotFound", () => Effect.void));
232 yield* waitUntilParameterGone(name);
233 current = undefined;
234 }
235
236 if (current === undefined) {
237 const created = yield* parametermanager
238 .createProjectsLocationsParameters({
239 parent: `projects/${env.project}/locations/${location}`,
240 parameterId,
241 body: {
242 labels: desiredLabels,
243 format,
244 kmsKey: news.kmsKey,
245 },
246 })
247 .pipe(Effect.catchTag("Conflict", () => getParameter(name)));
248 current = (yield* getParameter(name)) ?? created ?? undefined;
249 }
250
251 if (current === undefined) {
252 return yield* new ParameterNotResolved({ resourceName: name });
253 }
254
255 const observedLabels = tagRecord(current.labels);
256 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
257 const labelsChanged = upsert.length > 0 || removed.length > 0;
258 const kmsChanged = !sameText(current.kmsKey, desiredKmsKey);
259
260 if (labelsChanged || kmsChanged) {
261 yield* parametermanager.patchProjectsLocationsParameters({
262 name,
263 updateMask: [labelsChanged ? "labels" : undefined, kmsChanged ? "kmsKey" : undefined]
264 .filter((field): field is string => field !== undefined)
265 .join(","),
266 body: {
267 name,
268 labels: desiredLabels,
269 kmsKey: news.kmsKey,
270 },
271 });
272 current = (yield* getParameter(name)) ?? current;
273 }
274
275 return toAttrs(current, env.project);
276 }),
277
278 delete: Effect.fn(function* ({ output }) {
279 const name = output.name;
280 yield* deleteVersions(name);
281 yield* parametermanager.deleteProjectsLocationsParameters({ name }).pipe(
282 Effect.retry({
283 while: (error) => error._tag === "Conflict",
284 times: 8,
285 schedule: Schedule.spaced("1 second"),
286 }),
287 Effect.catchTag(["NotFound", "BadRequest"], () => Effect.void),
288 );
289 yield* waitUntilParameterGone(name);
290 }),
291 });
292
293 export const parameterIdOf = (name: string) => lastSegment(name);