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

main
ts 283 lines 9.23 KB
Raw
1 import * as apim from "@distilled.cloud/gcp/apim_v1alpha";
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 Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 type GclbObservationSource,
12 ResourceNotResolved,
13 expandGclb,
14 hasAlchemyId,
15 listAtLocation,
16 collectPages,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 replaceOnIdentity,
21 resourceName,
22 sameJson,
23 toPhysicalId,
24 waitForOperation,
25 waitUntilExists,
26 waitUntilGone,
27 waitUntilReady,
28 } from "./internal.ts";
29
30 export type { GclbObservationSource, PscNetworkConfig } from "./internal.ts";
31
32 const COLLECTION = "observationSources";
33 const READY = new Set(["CREATED"]);
34
35 export type ObservationSourceProps = {
36 /**
37 * Observation source id (the `{source}` segment of
38 * `projects/{project}/locations/{location}/observationSources/{source}`).
39 * Must be 4-63 lowercase letters, digits, or hyphens. If omitted, a
40 * unique `alch-` prefixed name is generated. Immutable — changing it
41 * replaces the source.
42 */
43 observationSourceId?: string;
44 /**
45 * Region of the source (`us-central1`, …). Immutable — changing it
46 * replaces the source. The API currently allows one source per region.
47 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
48 */
49 location?: string;
50 /**
51 * GCLB observation source. Required. `pscNetworkConfigs` names the
52 * VPC and subnet used to attach PSC NEGs to Cloud Load Balancers.
53 * Immutable — changing it replaces the source.
54 */
55 gclbObservationSource: GclbObservationSource;
56 };
57
58 export type ObservationSource = Resource<
59 "GCP.Apim.ObservationSource",
60 ObservationSourceProps,
61 {
62 /** Full resource name. */
63 name: string;
64 /** Observation source id (last path segment). */
65 observationSourceId: string;
66 /** Project id. */
67 project: string;
68 /** Location id. */
69 location: string;
70 /** GCLB observation source configuration. */
71 gclbObservationSource: GclbObservationSource | undefined;
72 /** Server-reported state. */
73 state: string | undefined;
74 /** RFC3339 creation timestamp. */
75 createTime: string | undefined;
76 /** RFC3339 last-update timestamp. */
77 updateTime: string | undefined;
78 },
79 never,
80 Providers
81 >;
82
83 /**
84 * An API Observation source — configuration for collecting traffic from
85 * Cloud Load Balancers in a VPC. Sources have no labels, description,
86 * or update API; Alchemy stamps ownership into generated ids (`alch-`)
87 * so `list` / nuke can find them. Identity, location, and GCLB network
88 * config replace the resource.
89 *
90 * ### Creating an Observation Source
91 * **Example:** Observe a VPC via PSC
92 * ```typescript
93 * const source = yield* GCP.Apim.ObservationSource("Edge", {
94 * gclbObservationSource: {
95 * pscNetworkConfigs: [
96 * {
97 * network: network.selfLink,
98 * subnetwork: subnet.selfLink,
99 * },
100 * ],
101 * },
102 * });
103 * ```
104 *
105 * @resource
106 * @category Apim
107 */
108 export const ObservationSource = Resource<ObservationSource>("GCP.Apim.ObservationSource");
109
110 const toGclb = (
111 source: apim.GclbObservationSource | undefined,
112 ): GclbObservationSource | undefined => {
113 const configs = source?.pscNetworkConfigs ?? [];
114 if (configs.length === 0) return undefined;
115 return {
116 pscNetworkConfigs: configs.flatMap((config) =>
117 config.network && config.subnetwork
118 ? [
119 {
120 network: config.network,
121 subnetwork: config.subnetwork,
122 },
123 ]
124 : [],
125 ),
126 };
127 };
128
129 const toAttrs = (location: string, item: apim.ObservationSource, project: string) => {
130 const name = item.name ?? "";
131 const parsed = parseName(name, COLLECTION);
132 return {
133 name,
134 observationSourceId: parsed.id,
135 project: parsed.project || project,
136 location: parsed.location || location,
137 gclbObservationSource: toGclb(item.gclbObservationSource),
138 state: item.state,
139 createTime: item.createTime,
140 updateTime: item.updateTime,
141 };
142 };
143
144 const getByName = (name: string) =>
145 name.length === 0
146 ? Effect.undefined
147 : apim
148 .getProjectsLocationsObservationSources({ name })
149 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
150
151 const listOwned = (project: string, region: string) =>
152 listAtLocation(project, region, (parent) =>
153 collectPages(
154 apim.listProjectsLocationsObservationSources.pages({
155 parent,
156 pageSize: 1000,
157 }),
158 (page) => page.observationSources,
159 ),
160 ).pipe(
161 Effect.map((items) =>
162 items.filter((item) => hasAlchemyId(parseName(item.name ?? "", COLLECTION).id)),
163 ),
164 );
165
166 export const ObservationSourceProvider = () =>
167 Provider.succeed(ObservationSource, {
168 stables: ["name", "observationSourceId", "project", "location", "createTime"],
169
170 diff: Effect.fn(function* ({ news, olds, output }) {
171 if (!isResolved(news)) return undefined;
172 const env = yield* GcpEnvironment.current;
173 const location = normalizeLocation(
174 news.location ?? olds?.location ?? output?.location ?? env.region,
175 );
176 const previous = expandGclb(
177 olds?.gclbObservationSource ?? output?.gclbObservationSource,
178 env.project,
179 location,
180 );
181 const desired = expandGclb(news.gclbObservationSource, env.project, location);
182 return replaceOnIdentity({
183 previousId: olds?.observationSourceId ?? output?.observationSourceId,
184 nextId:
185 news.observationSourceId ?? olds?.observationSourceId ?? output?.observationSourceId,
186 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
187 nextLocation: location,
188 extra: previous !== undefined && !sameJson(previous, desired),
189 // MVP: one source per region, so replace must delete first.
190 deleteFirst: true,
191 });
192 }),
193
194 read: Effect.fn(function* ({ id, olds, output, previous }) {
195 const env = yield* GcpEnvironment.current;
196 const observationSourceId = yield* toPhysicalId(
197 id,
198 olds?.observationSourceId,
199 output?.observationSourceId,
200 "src",
201 );
202 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
203 const name =
204 output?.name ?? resourceName(env.project, location, COLLECTION, observationSourceId);
205 const existing = yield* getByName(name);
206 if (existing === undefined) return undefined;
207 const attrs = toAttrs(location, existing, env.project);
208 // No labels/description. Generated `alch-` ids are owned; an
209 // explicit id that already exists is Unowned unless we persisted it.
210 if (output !== undefined || hasAlchemyId(attrs.observationSourceId)) {
211 return attrs;
212 }
213 return unownedUnlessPrevious(attrs, previous, "name");
214 }),
215
216 list: () =>
217 Effect.gen(function* () {
218 const env = yield* GcpEnvironment.current;
219 const items = yield* listOwned(env.project, env.region);
220 return items.map((item) => toAttrs(env.region, item, env.project));
221 }),
222
223 reconcile: Effect.fn(function* ({ id, news, output }) {
224 const env = yield* GcpEnvironment.current;
225 const observationSourceId = yield* toPhysicalId(
226 id,
227 news.observationSourceId,
228 output?.observationSourceId,
229 "src",
230 );
231 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
232 const name = resourceName(env.project, location, COLLECTION, observationSourceId);
233 const gclbObservationSource = expandGclb(news.gclbObservationSource, env.project, location);
234
235 let current = yield* getByName(output?.name ?? name);
236
237 if (current === undefined) {
238 const created = yield* apim
239 .createProjectsLocationsObservationSources({
240 parent: parentOf(env.project, location),
241 observationSourceId,
242 body: {
243 gclbObservationSource,
244 },
245 })
246 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
247 if (created !== undefined) {
248 yield* waitForOperation(created);
249 }
250 current = yield* waitUntilExists(getByName(name), name);
251 }
252
253 if (current === undefined) {
254 return yield* new ResourceNotResolved({ resourceName: name });
255 }
256
257 current = yield* waitUntilReady(
258 getByName(current.name ?? name),
259 current.name ?? name,
260 (item) => item.state,
261 READY,
262 );
263
264 return toAttrs(location, current, env.project);
265 }),
266
267 delete: Effect.fn(function* ({ output }) {
268 const operation = yield* apim
269 .deleteProjectsLocationsObservationSources({ name: output.name })
270 .pipe(
271 Effect.retry({
272 while: (error) => error._tag === "Conflict",
273 times: 8,
274 schedule: Schedule.spaced("2 seconds"),
275 }),
276 Effect.catchTag("NotFound", () => Effect.undefined),
277 );
278 if (operation !== undefined) {
279 yield* waitForOperation(operation, { notFoundOk: true });
280 }
281 yield* waitUntilGone(getByName(output.name), output.name);
282 }),
283 });