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

main
ts 300 lines 10.3 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import { lastSegment, orgParent, organizationFromName, toResourceId } from "./names.ts";
12 import { waitForOperation } from "./operations.ts";
13 import { listOwnedInstances } from "./org.ts";
14
15 const MAX_NAME_LENGTH = 32;
16
17 export type InstancesNatAddressProps = {
18 /**
19 * Apigee organization id. Defaults to the current GCP project id.
20 * Immutable — changing it replaces the NAT address.
21 */
22 organization?: string;
23 /**
24 * Parent instance id or full name
25 * (`organizations/{org}/instances/{instance}`). Immutable — changing it
26 * replaces the NAT address.
27 */
28 instance: string;
29 /**
30 * NAT address id (the `{nataddress}` segment of
31 * `organizations/{org}/instances/{instance}/natAddresses/{nataddress}`).
32 * If omitted, a unique name is generated from the stack, stage, and
33 * logical id. Immutable — changing it replaces the NAT address.
34 */
35 natAddressId?: string;
36 /**
37 * When true, activate the address after it reaches `RESERVED` so the
38 * instance uses it for Internet egress. Activation is one-way.
39 * @default false
40 */
41 activate?: boolean;
42 };
43
44 export type InstancesNatAddress = Resource<
45 "GCP.Apigee.InstancesNatAddress",
46 InstancesNatAddressProps,
47 {
48 /** Full resource name `organizations/{org}/instances/{instance}/natAddresses/{nataddress}`. */
49 name: string;
50 /** NAT address id (last path segment). */
51 natAddressId: string;
52 /** Parent instance id. */
53 instanceId: string;
54 /** Apigee organization id. */
55 organization: string;
56 /** Provisioned static IPv4 address, if assigned. */
57 ipAddress: string | undefined;
58 /** Server-reported state (`CREATING`, `RESERVED`, `ACTIVE`, `DELETING`). */
59 state: string | undefined;
60 },
61 never,
62 Providers
63 >;
64
65 /**
66 * A static NAT address on an Apigee runtime instance.
67 *
68 * NAT addresses have no labels or description. `list` enumerates
69 * addresses on alchemy-owned instances so `pnpm nuke:gcp` can find
70 * leaked rows. Organization, instance, and name are identity — changing
71 * them replaces the address. `activate` updates in place (RESERVED →
72 * ACTIVE) and cannot be reversed.
73 *
74 * ### Creating a NAT Address
75 * **Example:** Reserve a NAT address on a runtime instance
76 * ```typescript
77 * const runtime = yield* GCP.Apigee.Instance("Runtime", {});
78 * const nat = yield* GCP.Apigee.InstancesNatAddress("Egress", {
79 * instance: runtime.name,
80 * });
81 * ```
82 *
83 * **Example:** Reserve and activate
84 * ```typescript
85 * const nat = yield* GCP.Apigee.InstancesNatAddress("Egress", {
86 * instance: runtime.name,
87 * natAddressId: "app-egress",
88 * activate: true,
89 * });
90 * ```
91 *
92 * @resource
93 * @category Apigee
94 */
95 export const InstancesNatAddress = Resource<InstancesNatAddress>("GCP.Apigee.InstancesNatAddress");
96
97 export class InstancesNatAddressNotResolved extends Data.TaggedError(
98 "GCP.Apigee.InstancesNatAddressNotResolved",
99 )<{
100 resourceName: string;
101 }> {}
102
103 export class InstancesNatAddressNotReady extends Data.TaggedError(
104 "GCP.Apigee.InstancesNatAddressNotReady",
105 )<{
106 resourceName: string;
107 state: string;
108 }> {}
109
110 const instanceIdOf = (instance: string) => lastSegment(instance);
111
112 const instanceName = (organization: string, instance: string) =>
113 instance.includes("/") ? instance : `${orgParent(organization)}/instances/${instance}`;
114
115 const resourceName = (organization: string, instance: string, natAddressId: string) =>
116 `${instanceName(organization, instance)}/natAddresses/${natAddressId}`;
117
118 const toAttrs = (
119 address: apigee.GoogleCloudApigeeV1NatAddress,
120 organization: string,
121 instanceId: string,
122 ) => {
123 const raw = address.name ?? "";
124 const name = raw.includes("/") ? raw : resourceName(organization, instanceId, raw);
125 return {
126 name,
127 natAddressId: lastSegment(name),
128 instanceId,
129 organization: organizationFromName(name) ?? organization,
130 ipAddress: address.ipAddress,
131 state: address.state,
132 };
133 };
134
135 const getByName = (name: string) =>
136 apigee
137 .getOrganizationsInstancesNatAddresses({ name })
138 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
139
140 const listByInstance = (parent: string) =>
141 apigee.listOrganizationsInstancesNatAddresses
142 .pages({
143 parent,
144 pageSize: 1000,
145 })
146 .pipe(
147 Stream.flatMap((page) => Stream.fromIterable(page.natAddresses ?? [])),
148 Stream.runCollect,
149 Effect.map((chunk) => Array.from(chunk)),
150 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
151 Effect.succeed([] as apigee.GoogleCloudApigeeV1NatAddress[]),
152 ),
153 );
154
155 const waitUntilState = (name: string, allowed: ReadonlySet<string>) =>
156 getByName(name).pipe(
157 Effect.filterOrFail(
158 (address): address is apigee.GoogleCloudApigeeV1NatAddress => address !== undefined,
159 () => new InstancesNatAddressNotResolved({ resourceName: name }),
160 ),
161 Effect.filterOrFail(
162 (address) => allowed.has(address.state ?? "STATE_UNSPECIFIED"),
163 (address) =>
164 new InstancesNatAddressNotReady({
165 resourceName: name,
166 state: address.state ?? "STATE_UNSPECIFIED",
167 }),
168 ),
169 Effect.retry({
170 while: (error) =>
171 error._tag === "GCP.Apigee.InstancesNatAddressNotReady" ||
172 error._tag === "GCP.Apigee.InstancesNatAddressNotResolved",
173 times: 8,
174 schedule: Schedule.spaced("5 seconds"),
175 }),
176 );
177
178 export const InstancesNatAddressProvider = () =>
179 Provider.succeed(InstancesNatAddress, {
180 stables: ["name", "natAddressId", "instanceId", "organization"],
181
182 diff: Effect.fn(function* ({ news, olds, output }) {
183 if (!isResolved(news)) return undefined;
184 const previousId = olds?.natAddressId ?? output?.natAddressId;
185 const previousInstance = olds?.instance ?? output?.instanceId;
186 const previousOrg = olds?.organization ?? output?.organization;
187 if (
188 (previousId !== undefined &&
189 news.natAddressId !== undefined &&
190 news.natAddressId !== previousId) ||
191 (previousInstance !== undefined &&
192 instanceIdOf(news.instance) !== instanceIdOf(previousInstance)) ||
193 (previousOrg !== undefined &&
194 news.organization !== undefined &&
195 news.organization !== previousOrg)
196 ) {
197 return { action: "replace" as const, deleteFirst: true };
198 }
199 return undefined;
200 }),
201
202 read: Effect.fn(function* ({ id, olds, output }) {
203 const env = yield* GcpEnvironment.current;
204 const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project;
205 const instanceId = instanceIdOf(olds?.instance ?? output?.instanceId ?? "");
206 if (instanceId.length === 0) return undefined;
207 const natAddressId = yield* toResourceId(
208 id,
209 olds?.natAddressId,
210 output?.natAddressId,
211 MAX_NAME_LENGTH,
212 );
213 const name = output?.name ?? resourceName(organization, instanceId, natAddressId);
214 const existing = yield* getByName(name);
215 if (existing === undefined) return undefined;
216 return toAttrs(existing, organization, instanceId);
217 }),
218
219 list: () =>
220 Effect.gen(function* () {
221 const env = yield* GcpEnvironment.current;
222 const instances = yield* listOwnedInstances(env.project);
223 const pages = yield* Effect.forEach(
224 instances,
225 (instance) => {
226 const parent = instance.name?.includes("/")
227 ? instance.name
228 : `${orgParent(env.project)}/instances/${lastSegment(instance.name ?? "")}`;
229 const instanceId = lastSegment(parent);
230 return listByInstance(parent).pipe(
231 Effect.map((addresses) =>
232 addresses.map((address) => toAttrs(address, env.project, instanceId)),
233 ),
234 );
235 },
236 { concurrency: 4 },
237 );
238 return pages.flat();
239 }),
240
241 reconcile: Effect.fn(function* ({ id, news, output }) {
242 const env = yield* GcpEnvironment.current;
243 const organization = news.organization ?? output?.organization ?? env.project;
244 const instanceId = instanceIdOf(news.instance);
245 const natAddressId = yield* toResourceId(
246 id,
247 news.natAddressId,
248 output?.natAddressId,
249 MAX_NAME_LENGTH,
250 );
251 const parent = instanceName(organization, instanceId);
252 const name = resourceName(organization, instanceId, natAddressId);
253
254 let current = yield* getByName(output?.name ?? name);
255
256 if (current === undefined) {
257 const created = yield* apigee
258 .createOrganizationsInstancesNatAddresses({
259 parent,
260 body: { name: natAddressId },
261 })
262 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
263 if (created !== undefined) {
264 yield* waitForOperation(created, { alreadyExistsOk: true });
265 }
266 current = yield* getByName(name);
267 }
268
269 if (current === undefined) {
270 return yield* new InstancesNatAddressNotResolved({ resourceName: name });
271 }
272
273 if ((current.state ?? "") === "CREATING") {
274 current =
275 (yield* waitUntilState(name, new Set(["RESERVED", "ACTIVE"])).pipe(
276 Effect.catchTag("GCP.Apigee.InstancesNatAddressNotReady", () => getByName(name)),
277 )) ?? current;
278 }
279
280 if (news.activate === true && (current.state ?? "") === "RESERVED") {
281 const activated = yield* apigee.activateOrganizationsInstancesNatAddresses({
282 name: current.name?.includes("/") ? current.name : name,
283 body: {},
284 });
285 yield* waitForOperation(activated);
286 current = (yield* getByName(name)) ?? current;
287 }
288
289 return toAttrs(current, organization, instanceId);
290 }),
291
292 delete: Effect.fn(function* ({ output }) {
293 const deleted = yield* apigee
294 .deleteOrganizationsInstancesNatAddresses({ name: output.name })
295 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
296 if (deleted !== undefined) {
297 yield* waitForOperation(deleted, { notFoundOk: true });
298 }
299 }),
300 });