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

main
ts 287 lines 9.63 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 changedFields,
15 collectPages,
16 hasAlchemyLabelKeys,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 resourceName,
21 rfc1035,
22 toPhysicalId,
23 userLabels,
24 waitForOperation,
25 waitUntilGone,
26 waitUntilPresent,
27 } from "./internal.ts";
28
29 const COLLECTION = "meshes";
30
31 export type MeshEnvoyHeaders = networkservices.MeshEnvoyHeadersEnum | (string & {});
32
33 export type MeshProps = {
34 /**
35 * Mesh id (the `{mesh}` segment of
36 * `projects/{project}/locations/{location}/meshes/{mesh}`). If omitted,
37 * a unique name is generated from the stack, stage, and logical id.
38 * Must be 1-63 characters and not start with a number. Immutable —
39 * changing it replaces the mesh.
40 */
41 meshId?: string;
42 /**
43 * Location (`global`, `us-central1`, …). Meshes are typically
44 * `global`. Immutable — changing it replaces the mesh. `US-CENTRAL1`
45 * is accepted and normalized to `us-central1`.
46 * @default "global"
47 */
48 location?: string;
49 /**
50 * Human-readable description. Max 1024 characters.
51 */
52 description?: string;
53 /**
54 * Localhost port the sidecar proxy intercepts (1-65535). Unset uses
55 * `15001`. Sidecar deployments only.
56 */
57 interceptionPort?: number;
58 /**
59 * Whether Envoy inserts debug headers on upstream requests.
60 * `NONE` (default) or `DEBUG_HEADERS`.
61 */
62 envoyHeaders?: MeshEnvoyHeaders;
63 /**
64 * User labels. Alchemy ownership labels are merged in automatically.
65 */
66 labels?: Record<string, string>;
67 };
68
69 export type Mesh = Resource<
70 "GCP.NetworkServices.Mesh",
71 MeshProps,
72 {
73 /** Full resource name `projects/{project}/locations/{location}/meshes/{mesh}`. */
74 name: string;
75 /** Mesh id (last path segment). */
76 meshId: string;
77 /** Project id. */
78 project: string;
79 /** Location id (`global`, `us-central1`, …). */
80 location: string;
81 /** User-provided description. */
82 description: string | undefined;
83 /** Sidecar interception port, if set. */
84 interceptionPort: number | undefined;
85 /** Envoy debug-header insertion mode. */
86 envoyHeaders: string | undefined;
87 /** User labels (Alchemy ownership labels stripped). */
88 labels: Record<string, string>;
89 /** Server-defined resource URL. */
90 selfLink: string | undefined;
91 /** RFC3339 creation timestamp. */
92 createTime: string | undefined;
93 /** RFC3339 last-update timestamp. */
94 updateTime: string | undefined;
95 },
96 never,
97 Providers
98 >;
99
100 /**
101 * A Cloud Service Mesh configuration grouping for workload-to-workload
102 * traffic. Routes attached to the mesh decide how requests are routed
103 * inside this logical boundary.
104 *
105 * Changing `meshId` or `location` replaces the mesh. Description,
106 * labels, interception port, and Envoy header settings update in place.
107 *
108 * ### Creating a Mesh
109 * **Example:** Generated name
110 * ```typescript
111 * const mesh = yield* GCP.NetworkServices.Mesh("Sidecar", {});
112 * ```
113 *
114 * **Example:** Named mesh with interception port
115 * ```typescript
116 * const mesh = yield* GCP.NetworkServices.Mesh("Sidecar", {
117 * meshId: "app-mesh",
118 * description: "prod sidecar mesh",
119 * interceptionPort: 15001,
120 * labels: { env: "prod" },
121 * });
122 * ```
123 *
124 * @resource
125 * @category NetworkServices
126 */
127 export const Mesh = Resource<Mesh>("GCP.NetworkServices.Mesh");
128
129 const toAttrs = (mesh: networkservices.Mesh, project: string) => {
130 const name = mesh.name ?? "";
131 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
132 return {
133 name,
134 meshId: parsed.id,
135 project: parsed.project || project,
136 location: parsed.location || DEFAULT_GLOBAL,
137 description: mesh.description,
138 interceptionPort: mesh.interceptionPort,
139 envoyHeaders: mesh.envoyHeaders,
140 labels: userLabels(mesh.labels),
141 selfLink: mesh.selfLink,
142 createTime: mesh.createTime,
143 updateTime: mesh.updateTime,
144 };
145 };
146
147 const getByName = (name: string) =>
148 networkservices
149 .getProjectsLocationsMeshes({ name })
150 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
151
152 export const MeshProvider = () =>
153 Provider.succeed(Mesh, {
154 stables: ["name", "meshId", "project", "location", "createTime", "selfLink"],
155
156 diff: Effect.fn(function* ({ news, olds, output }) {
157 if (!isResolved(news)) return undefined;
158 const previousId = olds?.meshId ?? output?.meshId;
159 const nextId = news.meshId ? rfc1035(news.meshId, "mesh") : previousId;
160 const previousLocation = normalizeLocation(
161 olds?.location ?? output?.location,
162 DEFAULT_GLOBAL,
163 );
164 const nextLocation = normalizeLocation(
165 news.location ?? olds?.location ?? output?.location,
166 DEFAULT_GLOBAL,
167 );
168 if (
169 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
170 previousLocation !== nextLocation
171 ) {
172 return { action: "replace" as const };
173 }
174 return undefined;
175 }),
176
177 read: Effect.fn(function* ({ id, olds, output }) {
178 const env = yield* GcpEnvironment.current;
179 const meshId = yield* toPhysicalId(id, olds?.meshId, output?.meshId, "mesh");
180 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
181 const name = output?.name ?? resourceName(env.project, location, COLLECTION, meshId);
182 const existing = yield* getByName(name);
183 if (existing === undefined) return undefined;
184 const attrs = toAttrs(existing, env.project);
185 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
186 }),
187
188 list: () =>
189 Effect.gen(function* () {
190 const env = yield* GcpEnvironment.current;
191 const items = yield* collectPages(
192 networkservices.listProjectsLocationsMeshes.pages({
193 parent: parentOf(env.project, "-"),
194 pageSize: 1000,
195 returnPartialSuccess: true,
196 }),
197 (page) => page.meshes,
198 );
199 return items
200 .filter((item) => hasAlchemyLabelKeys(item.labels))
201 .map((item) => toAttrs(item, env.project));
202 }),
203
204 reconcile: Effect.fn(function* ({ id, news, output }) {
205 const env = yield* GcpEnvironment.current;
206 const meshId = yield* toPhysicalId(id, news.meshId, output?.meshId, "mesh");
207 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
208 const name = resourceName(env.project, location, COLLECTION, meshId);
209 const desiredLabels = {
210 ...toLabels(news.labels),
211 ...(yield* createInternalLabels(id)),
212 };
213
214 let current = yield* getByName(name);
215
216 if (current === undefined) {
217 const created = yield* networkservices
218 .createProjectsLocationsMeshes({
219 parent: parentOf(env.project, location),
220 meshId,
221 body: {
222 description: news.description,
223 labels: desiredLabels,
224 interceptionPort: news.interceptionPort,
225 envoyHeaders: news.envoyHeaders,
226 },
227 })
228 .pipe(
229 Effect.retry({
230 while: (error) => error._tag === "Conflict",
231 times: 5,
232 schedule: Schedule.spaced("2 seconds"),
233 }),
234 Effect.catchTag("Conflict", () => Effect.undefined),
235 );
236 if (created !== undefined) {
237 yield* waitForOperation(created);
238 }
239 current = yield* waitUntilPresent(getByName(name), name);
240 }
241
242 const observedLabels = tagRecord(current.labels);
243 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
244 const labelsChanged = upsert.length > 0 || removed.length > 0;
245 const updateMask = changedFields([
246 ["labels", labelsChanged],
247 ["description", (current.description ?? "") !== (news.description ?? "")],
248 ["interceptionPort", (current.interceptionPort ?? 0) !== (news.interceptionPort ?? 0)],
249 ["envoyHeaders", (current.envoyHeaders ?? "") !== (news.envoyHeaders ?? "")],
250 ]);
251
252 if (updateMask.length > 0) {
253 const operation = yield* networkservices.patchProjectsLocationsMeshes({
254 name: current.name ?? name,
255 updateMask: updateMask.join(","),
256 body: {
257 name: current.name ?? name,
258 labels: desiredLabels,
259 description: news.description,
260 interceptionPort: news.interceptionPort,
261 envoyHeaders: news.envoyHeaders,
262 },
263 });
264 yield* waitForOperation(operation);
265 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
266 }
267
268 return toAttrs(current, env.project);
269 }),
270
271 delete: Effect.fn(function* ({ output }) {
272 const operation = yield* networkservices
273 .deleteProjectsLocationsMeshes({ name: output.name })
274 .pipe(
275 Effect.retry({
276 while: (error) => error._tag === "Conflict",
277 times: 8,
278 schedule: Schedule.spaced("2 seconds"),
279 }),
280 Effect.catchTag("NotFound", () => Effect.undefined),
281 );
282 if (operation !== undefined) {
283 yield* waitForOperation(operation, { notFoundOk: true });
284 }
285 yield* waitUntilGone(getByName(output.name), output.name);
286 }),
287 });