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

main
ts 298 lines 9.84 KB
Raw
1 import * as networkservices from "@distilled.cloud/gcp/networkservices_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 DEFAULT_GLOBAL,
14 canonicalizeLink,
15 changedFields,
16 collectPages,
17 hasAlchemyLabelKeys,
18 linkKey,
19 normalizeLocation,
20 parentOf,
21 parseName,
22 resourceName,
23 rfc1035,
24 toPhysicalId,
25 userLabels,
26 waitForOperation,
27 waitUntilGone,
28 waitUntilPresent,
29 } from "./internal.ts";
30
31 const COLLECTION = "serviceBindings";
32
33 export type ServiceBindingProps = {
34 /**
35 * Binding id (the `{serviceBinding}` segment of
36 * `projects/{project}/locations/{location}/serviceBindings/{serviceBinding}`).
37 * If omitted, a unique name is generated from the stack, stage, and
38 * logical id. Immutable — changing it replaces the binding.
39 */
40 serviceBindingId?: string;
41 /**
42 * Location (`global`, `us-central1`, …). Immutable — changing it
43 * replaces the binding. `US-CENTRAL1` is accepted and normalized to
44 * `us-central1`.
45 * @default "global"
46 */
47 location?: string;
48 /**
49 * Human-readable description. Max 1024 characters.
50 */
51 description?: string;
52 /**
53 * Service Directory service resource name
54 * `projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}`.
55 * This field is for the deprecated Service Directory integration.
56 * Immutable — changing it replaces the binding.
57 */
58 service?: string;
59 /**
60 * User labels. Alchemy ownership labels are merged in automatically.
61 */
62 labels?: Record<string, string>;
63 };
64
65 export type ServiceBinding = Resource<
66 "GCP.NetworkServices.ServiceBinding",
67 ServiceBindingProps,
68 {
69 /** Full resource name `projects/{project}/locations/{location}/serviceBindings/{serviceBinding}`. */
70 name: string;
71 /** Binding id (last path segment). */
72 serviceBindingId: string;
73 /** Project id. */
74 project: string;
75 /** Location id (`global`, `us-central1`, …). */
76 location: string;
77 /** User-provided description. */
78 description: string | undefined;
79 /** Bound Service Directory service name, if set. */
80 service: string | undefined;
81 /** UUID of the validated Service Directory service, if populated. */
82 serviceId: string | undefined;
83 /** User labels (Alchemy ownership labels stripped). */
84 labels: Record<string, string>;
85 /** RFC3339 creation timestamp. */
86 createTime: string | undefined;
87 /** RFC3339 last-update timestamp. */
88 updateTime: string | undefined;
89 },
90 never,
91 Providers
92 >;
93
94 /**
95 * A ServiceBinding attaches a producer service (Service Directory, PSC,
96 * or Cloud Run) so Cloud Service Mesh or an Application Load Balancer
97 * can send traffic to it.
98 *
99 * Changing `serviceBindingId`, `location`, or `service` replaces the
100 * binding. Description and labels update in place.
101 *
102 * ### Creating a ServiceBinding
103 * **Example:** Named binding
104 * ```typescript
105 * const binding = yield* GCP.NetworkServices.ServiceBinding("Api", {
106 * location: "global",
107 * description: "prod api",
108 * labels: { env: "prod" },
109 * });
110 * ```
111 *
112 * @resource
113 * @category NetworkServices
114 */
115 export const ServiceBinding = Resource<ServiceBinding>("GCP.NetworkServices.ServiceBinding");
116
117 const toService = (service: string | undefined) => {
118 const trimmed = canonicalizeLink(service);
119 return trimmed.length > 0 ? trimmed : undefined;
120 };
121
122 const toAttrs = (binding: networkservices.ServiceBinding, project: string) => {
123 const name = binding.name ?? "";
124 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
125 return {
126 name,
127 serviceBindingId: parsed.id,
128 project: parsed.project || project,
129 location: parsed.location || DEFAULT_GLOBAL,
130 description: binding.description,
131 service: toService(binding.service),
132 serviceId: binding.serviceId,
133 labels: userLabels(binding.labels),
134 createTime: binding.createTime,
135 updateTime: binding.updateTime,
136 };
137 };
138
139 const getByName = (name: string) =>
140 networkservices
141 .getProjectsLocationsServiceBindings({ name })
142 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
143
144 export const ServiceBindingProvider = () =>
145 Provider.succeed(ServiceBinding, {
146 stables: [
147 "name",
148 "serviceBindingId",
149 "project",
150 "location",
151 "service",
152 "serviceId",
153 "createTime",
154 ],
155
156 diff: Effect.fn(function* ({ news, olds, output }) {
157 if (!isResolved(news)) return undefined;
158 const previousId = olds?.serviceBindingId ?? output?.serviceBindingId;
159 const nextId = news.serviceBindingId
160 ? rfc1035(news.serviceBindingId, "service-binding")
161 : previousId;
162 const previousLocation = normalizeLocation(
163 olds?.location ?? output?.location,
164 DEFAULT_GLOBAL,
165 );
166 const nextLocation = normalizeLocation(
167 news.location ?? olds?.location ?? output?.location,
168 DEFAULT_GLOBAL,
169 );
170 const previousService = linkKey(olds?.service ?? output?.service);
171 const nextService = linkKey(news.service);
172 if (
173 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
174 previousLocation !== nextLocation ||
175 (previousService.length > 0 && nextService.length > 0 && previousService !== nextService)
176 ) {
177 return { action: "replace" as const };
178 }
179 return undefined;
180 }),
181
182 read: Effect.fn(function* ({ id, olds, output }) {
183 const env = yield* GcpEnvironment.current;
184 const serviceBindingId = yield* toPhysicalId(
185 id,
186 olds?.serviceBindingId,
187 output?.serviceBindingId,
188 "service-binding",
189 );
190 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
191 const name =
192 output?.name ?? resourceName(env.project, location, COLLECTION, serviceBindingId);
193 const existing = yield* getByName(name);
194 if (existing === undefined) return undefined;
195 const attrs = toAttrs(existing, env.project);
196 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
197 }),
198
199 list: () =>
200 Effect.gen(function* () {
201 const env = yield* GcpEnvironment.current;
202 const items = yield* collectPages(
203 networkservices.listProjectsLocationsServiceBindings.pages({
204 parent: parentOf(env.project, "-"),
205 pageSize: 1000,
206 }),
207 (page) => page.serviceBindings,
208 );
209 return items
210 .filter((item) => hasAlchemyLabelKeys(item.labels))
211 .map((item) => toAttrs(item, env.project));
212 }),
213
214 reconcile: Effect.fn(function* ({ id, news, output }) {
215 const env = yield* GcpEnvironment.current;
216 const serviceBindingId = yield* toPhysicalId(
217 id,
218 news.serviceBindingId,
219 output?.serviceBindingId,
220 "service-binding",
221 );
222 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
223 const name = resourceName(env.project, location, COLLECTION, serviceBindingId);
224 const desiredLabels = {
225 ...toLabels(news.labels),
226 ...(yield* createInternalLabels(id)),
227 };
228 const service = toService(news.service);
229
230 let current = yield* getByName(name);
231
232 if (current === undefined) {
233 const created = yield* networkservices
234 .createProjectsLocationsServiceBindings({
235 parent: parentOf(env.project, location),
236 serviceBindingId,
237 body: {
238 description: news.description,
239 labels: desiredLabels,
240 service,
241 },
242 })
243 .pipe(
244 Effect.retry({
245 while: (error) => error._tag === "Conflict",
246 times: 5,
247 schedule: Schedule.spaced("2 seconds"),
248 }),
249 Effect.catchTag("Conflict", () => Effect.undefined),
250 );
251 if (created !== undefined) {
252 yield* waitForOperation(created);
253 }
254 current = yield* waitUntilPresent(getByName(name), name);
255 }
256
257 const observedLabels = tagRecord(current.labels);
258 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
259 const labelsChanged = upsert.length > 0 || removed.length > 0;
260 const updateMask = changedFields([
261 ["labels", labelsChanged],
262 ["description", (current.description ?? "") !== (news.description ?? "")],
263 ]);
264
265 if (updateMask.length > 0) {
266 const operation = yield* networkservices.patchProjectsLocationsServiceBindings({
267 name: current.name ?? name,
268 updateMask: updateMask.join(","),
269 body: {
270 name: current.name ?? name,
271 labels: desiredLabels,
272 description: news.description,
273 },
274 });
275 yield* waitForOperation(operation);
276 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
277 }
278
279 return toAttrs(current, env.project);
280 }),
281
282 delete: Effect.fn(function* ({ output }) {
283 const operation = yield* networkservices
284 .deleteProjectsLocationsServiceBindings({ name: output.name })
285 .pipe(
286 Effect.retry({
287 while: (error) => error._tag === "Conflict",
288 times: 8,
289 schedule: Schedule.spaced("2 seconds"),
290 }),
291 Effect.catchTag("NotFound", () => Effect.undefined),
292 );
293 if (operation !== undefined) {
294 yield* waitForOperation(operation, { notFoundOk: true });
295 }
296 yield* waitUntilGone(getByName(output.name), output.name);
297 }),
298 });