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

main
ts 202 lines 7.05 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 { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { lastSegment, orgParent, organizationFromName, toResourceId } from "./names.ts";
11
12 const MAX_NAME_LENGTH = 255;
13
14 export type KeyvaluemapsEntryProps = {
15 /**
16 * Apigee organization id. Defaults to the current GCP project id.
17 * Immutable — changing it replaces the entry.
18 */
19 organization?: string;
20 /**
21 * Parent key value map id or full name
22 * (`organizations/{org}/keyvaluemaps/{keyvaluemap}`). Immutable —
23 * changing it replaces the entry.
24 */
25 map: string;
26 /**
27 * Entry key (the `{entry}` segment of
28 * `organizations/{org}/keyvaluemaps/{keyvaluemap}/entries/{entry}`).
29 * If omitted, a unique name is generated from the stack, stage, and
30 * logical id. Immutable — changing it replaces the entry. Must not be
31 * `__alchemy` (reserved by {@link Keyvaluemap} for ownership).
32 */
33 entryId?: string;
34 /**
35 * Payload associated with the key, stored verbatim.
36 */
37 value: string;
38 };
39
40 export type KeyvaluemapsEntry = Resource<
41 "GCP.Apigee.KeyvaluemapsEntry",
42 KeyvaluemapsEntryProps,
43 {
44 /** Full resource name `organizations/{org}/keyvaluemaps/{map}/entries/{entry}`. */
45 name: string;
46 /** Entry key (last path segment). */
47 entryId: string;
48 /** Parent map id. */
49 mapId: string;
50 /** Apigee organization id. */
51 organization: string;
52 /** Payload associated with the key. */
53 value: string;
54 },
55 never,
56 Providers
57 >;
58
59 /**
60 * An organization-scoped Apigee key value map entry.
61 *
62 * Entries have no labels field and the value is read by proxies, so
63 * Alchemy stores it verbatim and identifies its entries by the generated
64 * key: `read` reports an entry with an explicit `entryId` as unowned
65 * (adopt it with `--adopt`). Organization, map, and key are identity —
66 * changing them replaces the entry. `value` updates in place.
67 *
68 * ### Creating an Entry
69 * **Example:** Generated key on a map
70 * ```typescript
71 * const kv = yield* GCP.Apigee.Keyvaluemap("Config", {});
72 * const entry = yield* GCP.Apigee.KeyvaluemapsEntry("ApiKey", {
73 * map: kv.name,
74 * value: "secret-value",
75 * });
76 * ```
77 *
78 * **Example:** Explicit key
79 * ```typescript
80 * const entry = yield* GCP.Apigee.KeyvaluemapsEntry("ApiKey", {
81 * map: kv.name,
82 * entryId: "api-key",
83 * value: "secret-value",
84 * });
85 * ```
86 *
87 * @resource
88 * @category Apigee
89 */
90 export const KeyvaluemapsEntry = Resource<KeyvaluemapsEntry>("GCP.Apigee.KeyvaluemapsEntry");
91
92 export class KeyvaluemapsEntryNotResolved extends Data.TaggedError(
93 "GCP.Apigee.KeyvaluemapsEntryNotResolved",
94 )<{
95 resourceName: string;
96 }> {}
97
98 const mapIdOf = (map: string) => lastSegment(map);
99
100 const mapName = (organization: string, map: string) =>
101 map.includes("/") ? map : `${orgParent(organization)}/keyvaluemaps/${map}`;
102
103 const resourceName = (organization: string, map: string, entryId: string) =>
104 `${mapName(organization, map)}/entries/${entryId}`;
105
106 const toAttrs = (
107 entry: apigee.GoogleCloudApigeeV1KeyValueEntry,
108 organization: string,
109 mapId: string,
110 ) => {
111 const raw = entry.name ?? "";
112 const name = raw.includes("/") ? raw : resourceName(organization, mapId, raw);
113 return {
114 name,
115 entryId: lastSegment(name),
116 mapId,
117 organization: organizationFromName(name) ?? organization,
118 value: entry.value ?? "",
119 };
120 };
121
122 const getByName = (name: string) =>
123 apigee
124 .getOrganizationsKeyvaluemapsEntries({ name })
125 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
126
127 export const KeyvaluemapsEntryProvider = () =>
128 Provider.succeed(KeyvaluemapsEntry, {
129 stables: ["name", "entryId", "mapId", "organization"],
130
131 diff: Effect.fn(function* ({ news, olds, output }) {
132 if (!isResolved(news)) return undefined;
133 const previousId = olds?.entryId ?? output?.entryId;
134 const previousMap = olds?.map ?? output?.mapId;
135 const previousOrg = olds?.organization ?? output?.organization;
136 if (
137 (previousId !== undefined && news.entryId !== undefined && news.entryId !== previousId) ||
138 (previousMap !== undefined && mapIdOf(news.map) !== mapIdOf(previousMap)) ||
139 (previousOrg !== undefined &&
140 news.organization !== undefined &&
141 news.organization !== previousOrg)
142 ) {
143 return { action: "replace" as const, deleteFirst: true };
144 }
145 return undefined;
146 }),
147
148 read: Effect.fn(function* ({ id, olds, output, previous }) {
149 const env = yield* GcpEnvironment.current;
150 const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project;
151 const mapId = mapIdOf(olds?.map ?? output?.mapId ?? "");
152 if (mapId.length === 0) return undefined;
153 const entryId = yield* toResourceId(id, olds?.entryId, output?.entryId, MAX_NAME_LENGTH);
154 const name = output?.name ?? resourceName(organization, mapId, entryId);
155 const existing = yield* getByName(name);
156 if (existing === undefined) return undefined;
157 const attrs = toAttrs(existing, organization, mapId);
158 const generated = yield* toResourceId(id, undefined, undefined, MAX_NAME_LENGTH);
159 return attrs.entryId === generated ? attrs : unownedUnlessPrevious(attrs, previous, "name");
160 }),
161
162 reconcile: Effect.fn(function* ({ id, news, output }) {
163 const env = yield* GcpEnvironment.current;
164 const organization = news.organization ?? output?.organization ?? env.project;
165 const mapId = mapIdOf(news.map);
166 const entryId = yield* toResourceId(id, news.entryId, output?.entryId, MAX_NAME_LENGTH);
167 const parent = mapName(organization, news.map);
168 const name = resourceName(organization, mapId, entryId);
169 const desiredValue = news.value;
170
171 let current = yield* getByName(output?.name ?? name);
172
173 if (current === undefined) {
174 const created = yield* apigee
175 .createOrganizationsKeyvaluemapsEntries({
176 parent,
177 body: { name: entryId, value: desiredValue },
178 })
179 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
180 current = created ?? undefined;
181 }
182
183 if (current === undefined) {
184 return yield* new KeyvaluemapsEntryNotResolved({ resourceName: name });
185 }
186
187 if ((current.value ?? "") !== desiredValue) {
188 current = yield* apigee.updateOrganizationsKeyvaluemapsEntries({
189 name: current.name?.includes("/") ? current.name : name,
190 body: { name: entryId, value: desiredValue },
191 });
192 }
193
194 return toAttrs(current, organization, mapId);
195 }),
196
197 delete: Effect.fn(function* ({ output }) {
198 yield* apigee
199 .deleteOrganizationsKeyvaluemapsEntries({ name: output.name })
200 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
201 }),
202 });