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

main
ts 261 lines 8.21 KB
Raw
1 import * as storagetransfer from "@distilled.cloud/gcp/storagetransfer_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 * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 agentPoolIdOf,
13 agentPoolName,
14 createOwnership,
15 DEFAULT_AGENT_POOL,
16 encodeOwnership,
17 fieldMask,
18 MAX_AGENT_POOL_DISPLAY_NAME,
19 getAgentPool,
20 hasOwnershipMarker,
21 listAgentPools,
22 ownedByAlchemy,
23 parseOwnership,
24 retryApiDisabled,
25 sameValue,
26 sanitizeAgentPoolId,
27 toAgentPoolId,
28 waitAgentPoolCreated,
29 waitAgentPoolGone,
30 } from "./internal.ts";
31
32 export type BandwidthLimit = {
33 /**
34 * Bandwidth rate in megabytes per second, distributed across all
35 * agents in the pool. Omit for no limit.
36 */
37 limitMbps?: string;
38 };
39
40 export type AgentPoolProps = {
41 /**
42 * Agent pool id (the `{agent_pool}` segment of
43 * `projects/{project}/agentPools/{agent_pool}`). If omitted, a unique
44 * name is generated from the stack, stage, and logical id. Must match
45 * `^(?!goog)[a-z]([a-z0-9-._~]*[a-z0-9])?$` and is at most 128
46 * characters. Immutable — changing it replaces the pool.
47 */
48 agentPoolId?: string;
49 /**
50 * Client-specified description (combined with Alchemy ownership, max
51 * 127 characters). Agent pools have no labels field, so ownership is
52 * stored in a `[alchemy …]` prefix and stripped from attributes.
53 */
54 displayName?: string;
55 /**
56 * Bandwidth cap for the pool. Unspecified means no limit.
57 */
58 bandwidthLimit?: BandwidthLimit;
59 };
60
61 export type AgentPool = Resource<
62 "GCP.StorageTransfer.AgentPool",
63 AgentPoolProps,
64 {
65 /** Full resource name `projects/{project}/agentPools/{agent_pool}`. */
66 name: string;
67 /** Agent pool id (last path segment). */
68 agentPoolId: string;
69 /** Project id. */
70 project: string;
71 /** User display name with the Alchemy ownership prefix stripped. */
72 displayName: string | undefined;
73 /** Pool state (`CREATING`, `CREATED`, `DELETING`). */
74 state: string | undefined;
75 /** Configured bandwidth limit, if any. */
76 bandwidthLimit: BandwidthLimit | undefined;
77 },
78 never,
79 Providers
80 >;
81
82 /**
83 * A Storage Transfer Service agent pool for on-premises (POSIX) agents.
84 *
85 * Agent pools have no labels field, so Alchemy stamps ownership into
86 * `displayName` for `list` / nuke. Name is identity — changing
87 * `agentPoolId` replaces the pool. `displayName` and `bandwidthLimit`
88 * update in place.
89 *
90 * ### Creating an Agent Pool
91 * **Example:** Generated id
92 * ```typescript
93 * const pool = yield* GCP.StorageTransfer.AgentPool("OnPrem", {
94 * displayName: "warehouse scanners",
95 * });
96 * ```
97 *
98 * **Example:** Named pool with a bandwidth cap
99 * ```typescript
100 * const pool = yield* GCP.StorageTransfer.AgentPool("OnPrem", {
101 * agentPoolId: "warehouse-scanners",
102 * displayName: "warehouse scanners",
103 * bandwidthLimit: { limitMbps: "120" },
104 * });
105 * ```
106 *
107 * ### Updating an Agent Pool
108 * Change props on the same logical id; the engine keeps the physical id.
109 *
110 * **Example:** Raise the bandwidth cap
111 * ```typescript
112 * const pool = yield* GCP.StorageTransfer.AgentPool("OnPrem", {
113 * displayName: "warehouse scanners",
114 * bandwidthLimit: { limitMbps: "250" },
115 * });
116 * ```
117 *
118 * @resource
119 * @category StorageTransfer
120 */
121 export const AgentPool = Resource<AgentPool>("GCP.StorageTransfer.AgentPool");
122
123 export class AgentPoolNotResolved extends Data.TaggedError(
124 "GCP.StorageTransfer.AgentPoolNotResolved",
125 )<{
126 resourceName: string;
127 }> {}
128
129 const toBandwidth = (
130 limit: storagetransfer.BandwidthLimit | BandwidthLimit | undefined,
131 ): BandwidthLimit | undefined => {
132 const limitMbps = limit?.limitMbps;
133 if (limitMbps === undefined || limitMbps.length === 0) return undefined;
134 return { limitMbps };
135 };
136
137 const toAttrs = (pool: storagetransfer.AgentPool, project: string) => {
138 const name = pool.name ?? "";
139 return {
140 name,
141 agentPoolId: agentPoolIdOf(name),
142 project,
143 displayName: parseOwnership(pool.displayName).text,
144 state: pool.state,
145 bandwidthLimit: toBandwidth(pool.bandwidthLimit),
146 };
147 };
148
149 export const AgentPoolProvider = () =>
150 Provider.succeed(AgentPool, {
151 stables: ["name", "agentPoolId", "project"],
152
153 diff: Effect.fn(function* ({ news, olds, output }) {
154 if (!isResolved(news)) return undefined;
155 const previous = olds?.agentPoolId ?? output?.agentPoolId;
156 if (
157 previous !== undefined &&
158 news.agentPoolId !== undefined &&
159 sanitizeAgentPoolId(news.agentPoolId) !== previous
160 ) {
161 return { action: "replace" as const, deleteFirst: false };
162 }
163 return undefined;
164 }),
165
166 read: Effect.fn(function* ({ id, olds, output }) {
167 const env = yield* GcpEnvironment.current;
168 const agentPoolId = yield* toAgentPoolId(id, olds?.agentPoolId, output?.agentPoolId);
169 const name = output?.name ?? agentPoolName(env.project, agentPoolId);
170 const existing = yield* getAgentPool(name);
171 if (existing === undefined) return undefined;
172 const attrs = toAttrs(existing, env.project);
173 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
174 }),
175
176 list: () =>
177 Effect.gen(function* () {
178 const env = yield* GcpEnvironment.current;
179 const pools = yield* listAgentPools(env.project);
180 return pools
181 .filter(
182 (pool) =>
183 agentPoolIdOf(pool.name ?? "") !== DEFAULT_AGENT_POOL &&
184 hasOwnershipMarker(pool.displayName),
185 )
186 .map((pool) => toAttrs(pool, env.project));
187 }),
188
189 reconcile: Effect.fn(function* ({ id, news, output }) {
190 const env = yield* GcpEnvironment.current;
191 const agentPoolId = yield* toAgentPoolId(id, news.agentPoolId, output?.agentPoolId);
192 const name = agentPoolName(env.project, agentPoolId);
193 const ownership = yield* createOwnership(id);
194 const desiredDisplayName = encodeOwnership(
195 ownership,
196 news.displayName,
197 MAX_AGENT_POOL_DISPLAY_NAME,
198 );
199 const desiredLimit = toBandwidth(news.bandwidthLimit);
200
201 let current = yield* getAgentPool(output?.name ?? name);
202 if (current?.state === "DELETING") {
203 yield* waitAgentPoolGone(name);
204 current = undefined;
205 }
206
207 if (current === undefined) {
208 const created = yield* retryApiDisabled(
209 storagetransfer.createProjectsAgentPools({
210 projectId: env.project,
211 agentPoolId,
212 body: {
213 displayName: desiredDisplayName,
214 bandwidthLimit: desiredLimit,
215 },
216 }),
217 ).pipe(Effect.catchTag("Conflict", () => getAgentPool(name)));
218 current = created ?? undefined;
219 }
220
221 if (current !== undefined && current.state === "CREATING") {
222 current = (yield* waitAgentPoolCreated(name)) ?? current;
223 }
224
225 if (current === undefined) {
226 return yield* new AgentPoolNotResolved({ resourceName: name });
227 }
228
229 const displayChanged = (current.displayName ?? "") !== desiredDisplayName;
230 const limitChanged = !sameValue(toBandwidth(current.bandwidthLimit), desiredLimit);
231 const updateMask = fieldMask([
232 displayChanged ? "display_name" : undefined,
233 limitChanged ? "bandwidth_limit" : undefined,
234 ]);
235
236 if (updateMask.length > 0) {
237 current = yield* storagetransfer.patchProjectsAgentPools({
238 name: current.name ?? name,
239 updateMask,
240 body: {
241 displayName: desiredDisplayName,
242 bandwidthLimit: desiredLimit,
243 },
244 });
245 }
246
247 return toAttrs(current, env.project);
248 }),
249
250 delete: Effect.fn(function* ({ output }) {
251 if (output.agentPoolId === DEFAULT_AGENT_POOL) return;
252 yield* storagetransfer.deleteProjectsAgentPools({ name: output.name }).pipe(
253 Effect.catchTag("NotFound", () => Effect.void),
254 Effect.retry({
255 while: (error) => error._tag === "Conflict",
256 times: 8,
257 schedule: Schedule.exponential("500 millis"),
258 }),
259 );
260 }),
261 });