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

main
ts 335 lines 11.3 KB
Raw
1 import * as networksecurity from "@distilled.cloud/gcp/networksecurity_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 Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import {
15 lastSegment,
16 normalizeLocation,
17 parentOf,
18 parseResourceName,
19 resourceName,
20 toId,
21 toResourcePath,
22 userLabels,
23 } from "./names.ts";
24 import { waitForOperation } from "./operations.ts";
25
26 const COLLECTION = "sacAttachments";
27
28 export type SacAttachmentProps = {
29 /**
30 * Attachment id (the `{sacAttachment}` segment of
31 * `projects/{project}/locations/{location}/sacAttachments/{sacAttachment}`).
32 * If omitted, a unique RFC1035 name is generated from the stack, stage,
33 * and logical id. Immutable — changing it replaces the attachment.
34 */
35 sacAttachmentId?: string;
36 /**
37 * Region of the attachment (e.g. `us-central1`). Immutable — changing
38 * it replaces the attachment. `US-CENTRAL1` is accepted and
39 * normalized to `us-central1`.
40 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
41 */
42 location?: string;
43 /**
44 * SAC realm that owns the attachment, as an id or full resource name.
45 * The realm must already be paired with its SSE partner's realm;
46 * otherwise create fails with `SacRealmNotPaired`. Immutable — changing
47 * it replaces the attachment.
48 */
49 sacRealm: string;
50 /**
51 * NCC Gateway spoke associated with the attachment, as an id or full
52 * resource name. Immutable — changing it replaces the attachment.
53 */
54 nccGateway: string;
55 /**
56 * User labels. Alchemy ownership labels are merged in automatically.
57 * The SAC attachment API has no patch, so changing labels replaces
58 * the attachment.
59 */
60 labels?: Record<string, string>;
61 };
62
63 export type SacAttachment = Resource<
64 "GCP.NetworkSecurity.SacAttachment",
65 SacAttachmentProps,
66 {
67 /** Full resource name. */
68 name: string;
69 /** Attachment id (last path segment). */
70 sacAttachmentId: string;
71 /** Project id. */
72 project: string;
73 /** Region id. */
74 location: string;
75 /** Owning SAC realm resource name. */
76 sacRealm: string | undefined;
77 /** Associated NCC Gateway spoke resource name. */
78 nccGateway: string | undefined;
79 /** User labels (Alchemy ownership labels stripped). */
80 labels: Record<string, string>;
81 /** Server-reported lifecycle state. */
82 state: string | undefined;
83 /** RFC3339 creation timestamp. */
84 createTime: string | undefined;
85 /** RFC3339 last-update timestamp. */
86 updateTime: string | undefined;
87 },
88 never,
89 Providers
90 >;
91
92 /**
93 * A Secure Access Connect (SAC) attachment — binds an NCC Gateway to a
94 * SAC realm so SSE traffic can be processed.
95 *
96 * The realm must first be paired with the SSE partner's realm (Palo Alto
97 * Prisma Access / Symantec) on the partner side; an unpaired realm is
98 * rejected with `SacRealmNotPaired`.
99 *
100 * The create API has no patch; changing `sacAttachmentId`, `location`,
101 * `sacRealm`, `nccGateway`, or labels replaces the attachment.
102 *
103 * ### Creating an Attachment
104 * **Example:** Generated name
105 * ```typescript
106 * const attachment = yield* GCP.NetworkSecurity.SacAttachment("PrismaLink", {
107 * sacRealm: realm.name,
108 * nccGateway: gateway.name,
109 * });
110 * ```
111 *
112 * **Example:** Named attachment with labels
113 * ```typescript
114 * const attachment = yield* GCP.NetworkSecurity.SacAttachment("PrismaLink", {
115 * sacAttachmentId: "app-prisma-link",
116 * location: "us-central1",
117 * sacRealm: realm.name,
118 * nccGateway: gateway.name,
119 * labels: { env: "prod" },
120 * });
121 * ```
122 *
123 * @resource
124 * @category NetworkSecurity
125 */
126 export const SacAttachment = Resource<SacAttachment>("GCP.NetworkSecurity.SacAttachment");
127
128 export class SacAttachmentNotResolved extends Data.TaggedError(
129 "GCP.NetworkSecurity.SacAttachmentNotResolved",
130 )<{
131 resourceName: string;
132 }> {}
133
134 export class SacAttachmentStillExists extends Data.TaggedError(
135 "GCP.NetworkSecurity.SacAttachmentStillExists",
136 )<{
137 resourceName: string;
138 }> {}
139
140 const toAttrs = (attachment: networksecurity.SACAttachment, project: string, region: string) => {
141 const name = attachment.name ?? "";
142 const parsed = parseResourceName(name, COLLECTION);
143 return {
144 name,
145 sacAttachmentId: parsed.id,
146 project: parsed.project || project,
147 location: parsed.location || region,
148 sacRealm: attachment.sacRealm,
149 nccGateway: attachment.nccGateway,
150 labels: userLabels(attachment.labels),
151 state: attachment.state,
152 createTime: attachment.createTime,
153 updateTime: attachment.updateTime,
154 };
155 };
156
157 const getByName = (name: string) =>
158 networksecurity
159 .getProjectsLocationsSacAttachments({ name })
160 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
161
162 const waitUntilReady = (name: string) =>
163 getByName(name).pipe(
164 Effect.filterOrFail(
165 (attachment): attachment is networksecurity.SACAttachment => attachment !== undefined,
166 () => new SacAttachmentNotResolved({ resourceName: name }),
167 ),
168 Effect.retry({
169 while: (error) => error._tag === "GCP.NetworkSecurity.SacAttachmentNotResolved",
170 times: 10,
171 schedule: Schedule.spaced("2 seconds"),
172 }),
173 );
174
175 const waitUntilGone = (name: string) =>
176 getByName(name).pipe(
177 Effect.flatMap((attachment) =>
178 attachment === undefined
179 ? Effect.void
180 : Effect.fail(new SacAttachmentStillExists({ resourceName: name })),
181 ),
182 Effect.retry({
183 while: (error) => error._tag === "GCP.NetworkSecurity.SacAttachmentStillExists",
184 times: 10,
185 schedule: Schedule.spaced("2 seconds"),
186 }),
187 );
188
189 const listOwned = (project: string, region: string) =>
190 networksecurity.listProjectsLocationsSacAttachments
191 .pages({
192 parent: parentOf(project, "-"),
193 pageSize: 1000,
194 })
195 .pipe(
196 Stream.flatMap((page) => Stream.fromIterable(page.sacAttachments ?? [])),
197 Stream.filter((attachment) =>
198 Object.keys(attachment.labels ?? {}).some((key) => key.startsWith("alchemy-")),
199 ),
200 Stream.map((attachment) => toAttrs(attachment, project, region)),
201 Stream.runCollect,
202 Effect.map((chunk) => Array.from(chunk)),
203 Effect.catchTag("NotFound", () => Effect.succeed([])),
204 );
205
206 export const SacAttachmentProvider = () =>
207 Provider.succeed(SacAttachment, {
208 stables: [
209 "name",
210 "sacAttachmentId",
211 "project",
212 "location",
213 "sacRealm",
214 "nccGateway",
215 "createTime",
216 ],
217
218 diff: Effect.fn(function* ({ news, olds, output }) {
219 if (!isResolved(news)) return undefined;
220 const env = yield* GcpEnvironment.current;
221 const previousId = olds?.sacAttachmentId ?? output?.sacAttachmentId;
222 const nextId = news.sacAttachmentId ?? previousId;
223 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
224 const nextLocation = normalizeLocation(
225 news.location ?? olds?.location ?? output?.location,
226 env.region,
227 );
228 const previousRealm = lastSegment(olds?.sacRealm ?? output?.sacRealm ?? "");
229 const nextRealm = lastSegment(news.sacRealm);
230 const previousGateway = lastSegment(olds?.nccGateway ?? output?.nccGateway ?? "");
231 const nextGateway = lastSegment(news.nccGateway);
232 const previousLabels = { ...toLabels(olds?.labels) };
233 const nextLabels = { ...toLabels(news.labels) };
234 const { upsert, removed } = diffLabels(previousLabels, nextLabels);
235 const labelsChanged = upsert.length > 0 || removed.length > 0;
236 const replace =
237 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
238 previousLocation !== nextLocation ||
239 (previousRealm.length > 0 && previousRealm !== nextRealm) ||
240 (previousGateway.length > 0 && previousGateway !== nextGateway) ||
241 labelsChanged;
242 if (!replace) return undefined;
243 return { action: "replace" as const };
244 }),
245
246 read: Effect.fn(function* ({ id, olds, output }) {
247 const env = yield* GcpEnvironment.current;
248 const sacAttachmentId = yield* toId(
249 id,
250 olds?.sacAttachmentId,
251 output?.sacAttachmentId,
252 "saca",
253 );
254 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
255 const name = output?.name ?? resourceName(env.project, location, COLLECTION, sacAttachmentId);
256 const existing = yield* getByName(name);
257 if (existing === undefined) return undefined;
258 const attrs = toAttrs(existing, env.project, env.region);
259 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
260 }),
261
262 list: () =>
263 Effect.gen(function* () {
264 const env = yield* GcpEnvironment.current;
265 return yield* listOwned(env.project, env.region);
266 }),
267
268 reconcile: Effect.fn(function* ({ id, news, output }) {
269 const env = yield* GcpEnvironment.current;
270 const sacAttachmentId = yield* toId(
271 id,
272 news.sacAttachmentId,
273 output?.sacAttachmentId,
274 "saca",
275 );
276 const location = normalizeLocation(news.location ?? output?.location, env.region);
277 const name = resourceName(env.project, location, COLLECTION, sacAttachmentId);
278 const sacRealm = toResourcePath(news.sacRealm);
279 const nccGateway = toResourcePath(news.nccGateway);
280 const desiredLabels = {
281 ...toLabels(news.labels),
282 ...(yield* createInternalLabels(id)),
283 };
284
285 let current = yield* getByName(name);
286
287 if (current === undefined) {
288 const created = yield* networksecurity
289 .createProjectsLocationsSacAttachments({
290 parent: parentOf(env.project, location),
291 sacAttachmentId,
292 body: {
293 sacRealm,
294 nccGateway,
295 labels: desiredLabels,
296 },
297 })
298 .pipe(
299 Effect.retry({
300 while: (error) => error._tag === "Conflict",
301 times: 5,
302 schedule: Schedule.spaced("2 seconds"),
303 }),
304 Effect.catchTag("Conflict", () => Effect.undefined),
305 );
306 if (created !== undefined) {
307 yield* waitForOperation(created);
308 }
309 current = yield* waitUntilReady(name);
310 }
311
312 if (current === undefined) {
313 return yield* new SacAttachmentNotResolved({ resourceName: name });
314 }
315
316 return toAttrs(current, env.project, env.region);
317 }),
318
319 delete: Effect.fn(function* ({ output }) {
320 const operation = yield* networksecurity
321 .deleteProjectsLocationsSacAttachments({ name: output.name })
322 .pipe(
323 Effect.retry({
324 while: (error) => error._tag === "Conflict",
325 times: 8,
326 schedule: Schedule.spaced("2 seconds"),
327 }),
328 Effect.catchTag("NotFound", () => Effect.undefined),
329 );
330 if (operation !== undefined) {
331 yield* waitForOperation(operation, { notFoundOk: true });
332 }
333 yield* waitUntilGone(output.name);
334 }),
335 });