@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, 04:45 UTC

main
ts 267 lines 9.32 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
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 * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import { lastSegment, orgParent, resolveOrgId, toPhysicalId } from "./operations.ts";
12
13 const MAX_NAME_LENGTH = 255;
14 const OWNERSHIP_KEY = "__alchemy";
15
16 export type ApisKeyvaluemapsEntryProps = {
17 /**
18 * Apigee organization id. Defaults to the GCP project id. Immutable.
19 */
20 organizationId?: string;
21 /**
22 * Parent API proxy id. Immutable.
23 */
24 api: string;
25 /**
26 * Parent key value map id. Immutable.
27 */
28 map: string;
29 /**
30 * Entry key. If omitted, a unique name is generated. Immutable.
31 */
32 entryId?: string;
33 /**
34 * Value stored for this key.
35 */
36 value: string;
37 };
38
39 export type ApisKeyvaluemapsEntry = Resource<
40 "GCP.Apigee.ApisKeyvaluemapsEntry",
41 ApisKeyvaluemapsEntryProps,
42 {
43 /** Full resource name `.../keyvaluemaps/{map}/entries/{entry}`. */
44 name: string;
45 /** Entry key. */
46 entryId: string;
47 /** Parent map id. */
48 mapId: string;
49 /** Parent API proxy id. */
50 apiId: string;
51 /** Organization id. */
52 organizationId: string;
53 /** Project id. */
54 project: string;
55 /** Stored value. */
56 value: string;
57 },
58 never,
59 Providers
60 >;
61
62 /**
63 * A key/value entry in an API-proxy-scoped Apigee key value map.
64 *
65 * Entries have no labels. Alchemy treats entries inside a map that
66 * carries the `__alchemy` sentinel as owned so `list` / nuke can find
67 * them. Changing `entryId`, `map`, `api`, or `organizationId` replaces
68 * the entry. The reserved key `__alchemy` is used for map ownership and
69 * is not a user entry.
70 *
71 * ### Creating an Entry
72 * **Example:** Put a config value
73 * ```typescript
74 * const entry = yield* GCP.Apigee.ApisKeyvaluemapsEntry("Timeout", {
75 * api: proxy.apiId,
76 * map: map.mapId,
77 * entryId: "timeout-ms",
78 * value: "5000",
79 * });
80 * ```
81 *
82 * @resource
83 * @category Apigee
84 */
85 export const ApisKeyvaluemapsEntry = Resource<ApisKeyvaluemapsEntry>(
86 "GCP.Apigee.ApisKeyvaluemapsEntry",
87 );
88
89 export class ApisKeyvaluemapsEntryNotResolved extends Data.TaggedError(
90 "GCP.Apigee.ApisKeyvaluemapsEntryNotResolved",
91 )<{
92 resourceName: string;
93 }> {}
94
95 const resourceName = (organizationId: string, apiId: string, mapId: string, entryId: string) =>
96 `${orgParent(organizationId)}/apis/${lastSegment(apiId)}/keyvaluemaps/${lastSegment(mapId)}/entries/${entryId}`;
97
98 const mapName = (organizationId: string, apiId: string, mapId: string) =>
99 `${orgParent(organizationId)}/apis/${lastSegment(apiId)}/keyvaluemaps/${lastSegment(mapId)}`;
100
101 const toAttrs = (
102 entry: apigee.GoogleCloudApigeeV1KeyValueEntry,
103 project: string,
104 organizationId: string,
105 apiId: string,
106 mapId: string,
107 name: string,
108 ) => ({
109 name,
110 entryId: lastSegment(entry.name ?? name),
111 mapId: lastSegment(mapId),
112 apiId: lastSegment(apiId),
113 organizationId,
114 project,
115 value: entry.value ?? "",
116 });
117
118 const getByName = (name: string) =>
119 apigee
120 .getOrganizationsApisKeyvaluemapsEntries({ name })
121 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
122
123 const mapIsOwned = (parent: string) =>
124 apigee
125 .getOrganizationsApisKeyvaluemapsEntries({
126 name: `${parent}/entries/${OWNERSHIP_KEY}`,
127 })
128 .pipe(
129 Effect.map(() => true),
130 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.succeed(false)),
131 );
132
133 export const ApisKeyvaluemapsEntryProvider = () =>
134 Provider.succeed(ApisKeyvaluemapsEntry, {
135 stables: ["name", "entryId", "mapId", "apiId", "organizationId", "project"],
136
137 diff: Effect.fn(function* ({ news, olds, output }) {
138 if (!isResolved(news)) return undefined;
139 const previousId = olds?.entryId ?? output?.entryId;
140 const previousMap = olds?.map ? lastSegment(olds.map) : output?.mapId;
141 const previousApi = olds?.api ? lastSegment(olds.api) : output?.apiId;
142 const previousOrg = olds?.organizationId ?? output?.organizationId;
143 if (
144 (previousId !== undefined && news.entryId !== undefined && news.entryId !== previousId) ||
145 (previousMap !== undefined && lastSegment(news.map) !== previousMap) ||
146 (previousApi !== undefined && lastSegment(news.api) !== previousApi) ||
147 (previousOrg !== undefined &&
148 news.organizationId !== undefined &&
149 news.organizationId !== previousOrg)
150 ) {
151 return { action: "replace" as const, deleteFirst: true };
152 }
153 return undefined;
154 }),
155
156 read: Effect.fn(function* ({ id, olds, output, previous }) {
157 const env = yield* GcpEnvironment.current;
158 const organizationId =
159 olds?.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
160 const apiId = lastSegment(olds?.api ?? output?.apiId ?? "");
161 const mapId = lastSegment(olds?.map ?? output?.mapId ?? "");
162 if (apiId.length === 0 || mapId.length === 0) return undefined;
163 const entryId = yield* toPhysicalId(id, olds?.entryId, output?.entryId, MAX_NAME_LENGTH);
164 const name = output?.name ?? resourceName(organizationId, apiId, mapId, entryId);
165 const existing = yield* getByName(name);
166 if (existing === undefined) return undefined;
167 const attrs = toAttrs(existing, env.project, organizationId, apiId, mapId, name);
168 const owned = yield* mapIsOwned(mapName(organizationId, apiId, mapId));
169 return owned ? attrs : unownedUnlessPrevious(attrs, previous, "name");
170 }),
171
172 list: () =>
173 Effect.gen(function* () {
174 const env = yield* GcpEnvironment.current;
175 const organizationId = yield* resolveOrgId(env.project);
176 const page = yield* apigee
177 .listOrganizationsApis({
178 parent: orgParent(organizationId),
179 includeMetaData: true,
180 })
181 .pipe(
182 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
183 Effect.succeed({ proxies: [] }),
184 ),
185 );
186 const owned = [];
187 for (const proxy of page.proxies ?? []) {
188 if (!Object.keys(proxy.labels ?? {}).some((key) => key.startsWith("alchemy-"))) {
189 continue;
190 }
191 const apiId = lastSegment(proxy.name ?? "");
192 if (apiId.length === 0) continue;
193 const parent = mapName(organizationId, apiId, apiId);
194 if (!(yield* mapIsOwned(parent))) continue;
195 const entries = yield* apigee.listOrganizationsApisKeyvaluemapsEntries
196 .pages({
197 parent,
198 pageSize: 100,
199 })
200 .pipe(
201 Stream.flatMap((item) => Stream.fromIterable(item.keyValueEntries ?? [])),
202 Stream.filter((entry) => lastSegment(entry.name ?? "") !== OWNERSHIP_KEY),
203 Stream.map((entry) => {
204 const name =
205 entry.name ??
206 resourceName(organizationId, apiId, apiId, lastSegment(entry.name ?? ""));
207 return toAttrs(
208 entry,
209 env.project,
210 organizationId,
211 apiId,
212 apiId,
213 name.includes("/") ? name : resourceName(organizationId, apiId, apiId, name),
214 );
215 }),
216 Stream.runCollect,
217 Effect.map((chunk) => Array.from(chunk)),
218 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.succeed([])),
219 );
220 owned.push(...entries);
221 }
222 return owned;
223 }),
224
225 reconcile: Effect.fn(function* ({ id, news, output }) {
226 const env = yield* GcpEnvironment.current;
227 const organizationId =
228 news.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
229 const apiId = lastSegment(news.api);
230 const mapId = lastSegment(news.map);
231 const entryId = yield* toPhysicalId(id, news.entryId, output?.entryId, MAX_NAME_LENGTH);
232 const name = resourceName(organizationId, apiId, mapId, entryId);
233 const parent = mapName(organizationId, apiId, mapId);
234
235 let current = yield* getByName(output?.name ?? name);
236
237 if (current === undefined) {
238 const created = yield* apigee
239 .createOrganizationsApisKeyvaluemapsEntries({
240 parent,
241 body: { name: entryId, value: news.value },
242 })
243 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
244 current = created ?? undefined;
245 }
246
247 if (current === undefined) {
248 return yield* new ApisKeyvaluemapsEntryNotResolved({ resourceName: name });
249 }
250
251 if ((current.value ?? "") !== news.value) {
252 current = yield* apigee.updateOrganizationsApisKeyvaluemapsEntries({
253 name,
254 body: { name: entryId, value: news.value },
255 });
256 }
257
258 return toAttrs(current, env.project, organizationId, apiId, mapId, name);
259 }),
260
261 delete: Effect.fn(function* ({ output }) {
262 if (output.entryId === OWNERSHIP_KEY) return;
263 yield* apigee
264 .deleteOrganizationsApisKeyvaluemapsEntries({ name: output.name })
265 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
266 }),
267 });