@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 346 lines 11 KB
Raw
1 import * as netapp from "@distilled.cloud/gcp/netapp_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 expandParent,
14 fieldMask,
15 listAtNested,
16 listLabeledPages,
17 normalizeLocation,
18 parseName,
19 replaceOnIdentity,
20 ResourceNotResolved,
21 toPhysicalId,
22 userLabels,
23 waitForDeleteOperation,
24 waitForOperation,
25 waitUntilExists,
26 waitUntilGone,
27 waitUntilReady,
28 } from "./internal.ts";
29
30 const DEFAULT_TYPE: netapp.QuotaRuleTypeEnum = "DEFAULT_USER_QUOTA";
31 const DEFAULT_DISK_LIMIT_MIB = 1024;
32
33 export type VolumesQuotaRuleProps = {
34 /**
35 * Parent volume. Full name
36 * `projects/{project}/locations/{location}/volumes/{volume}` or the
37 * volume id (combined with `location`). Immutable — changing it
38 * replaces the rule.
39 */
40 volume: string;
41 /**
42 * Region used when `volume` is a bare id.
43 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
44 */
45 location?: string;
46 /**
47 * Quota rule id (the `{quotaRule}` segment). If omitted, a unique
48 * RFC1035 name is generated from the stack, stage, and logical id.
49 * Immutable — changing it replaces the rule.
50 */
51 quotaRuleId?: string;
52 /**
53 * Quota type. Immutable — changing it replaces the rule.
54 * @default "DEFAULT_USER_QUOTA"
55 */
56 type?: netapp.QuotaRuleTypeEnum | (string & {});
57 /**
58 * Maximum disk space in MiB.
59 * @default 1024
60 */
61 diskLimitMib?: number;
62 /**
63 * Unix UID/GID, Windows SID, or omitted for a default quota.
64 * Immutable — changing it replaces the rule.
65 */
66 target?: string;
67 /**
68 * Human-readable description.
69 */
70 description?: string;
71 /**
72 * User labels. Alchemy ownership labels are merged in automatically.
73 */
74 labels?: Record<string, string>;
75 };
76
77 export type VolumesQuotaRule = Resource<
78 "GCP.NetApp.VolumesQuotaRule",
79 VolumesQuotaRuleProps,
80 {
81 /** Full resource name. */
82 name: string;
83 /** Quota rule id (last path segment). */
84 quotaRuleId: string;
85 /** Parent volume name. */
86 volume: string;
87 /** Project id. */
88 project: string;
89 /** Location id. */
90 location: string;
91 /** Quota type. */
92 type: string | undefined;
93 /** Disk limit in MiB. */
94 diskLimitMib: number | undefined;
95 /** Target user or group. */
96 target: string | undefined;
97 /** Human-readable description. */
98 description: string | undefined;
99 /** User labels (Alchemy ownership labels stripped). */
100 labels: Record<string, string>;
101 /** Server-reported state. */
102 state: string | undefined;
103 /** State details. */
104 stateDetails: string | undefined;
105 /** RFC3339 creation timestamp. */
106 createTime: string | undefined;
107 },
108 never,
109 Providers
110 >;
111
112 /**
113 * A Cloud NetApp Volumes quota rule that caps disk usage for a user or
114 * group on a volume.
115 *
116 * Changing `quotaRuleId`, `volume`, `location`, `type`, or `target`
117 * replaces the rule. Disk limit, description, and labels update in place.
118 *
119 * ### Creating a Quota Rule
120 * **Example:** Default user quota
121 * ```typescript
122 * const rule = yield* GCP.NetApp.VolumesQuotaRule("DefaultUser", {
123 * volume: volume.name,
124 * type: "DEFAULT_USER_QUOTA",
125 * diskLimitMib: 1024,
126 * });
127 * ```
128 *
129 * **Example:** Individual user quota
130 * ```typescript
131 * const rule = yield* GCP.NetApp.VolumesQuotaRule("Alice", {
132 * volume: volume.name,
133 * type: "INDIVIDUAL_USER_QUOTA",
134 * target: "1001",
135 * diskLimitMib: 2048,
136 * labels: { env: "prod" },
137 * });
138 * ```
139 *
140 * ### Updating a Quota Rule
141 * **Example:** Disk limit and labels
142 * ```typescript
143 * const rule = yield* GCP.NetApp.VolumesQuotaRule("DefaultUser", {
144 * volume: volume.name,
145 * diskLimitMib: 4096,
146 * description: "default user v2",
147 * labels: { env: "prod", team: "storage" },
148 * });
149 * ```
150 *
151 * @resource
152 * @category NetApp
153 */
154 export const VolumesQuotaRule = Resource<VolumesQuotaRule>("GCP.NetApp.VolumesQuotaRule");
155
156 const resourceName = (volume: string, quotaRuleId: string) => `${volume}/quotaRules/${quotaRuleId}`;
157
158 const toAttrs = (item: netapp.QuotaRule, project: string, region: string) => {
159 const name = item.name ?? "";
160 const parsed = parseName(name, "quotaRules", region);
161 return {
162 name,
163 quotaRuleId: parsed.id,
164 volume: parsed.parent,
165 project: parsed.project || project,
166 location: parsed.location,
167 type: item.type,
168 diskLimitMib: item.diskLimitMib,
169 target: item.target,
170 description: item.description,
171 labels: userLabels(item.labels),
172 state: item.state,
173 stateDetails: item.stateDetails,
174 createTime: item.createTime,
175 };
176 };
177
178 const getByName = (name: string) =>
179 netapp
180 .getProjectsLocationsVolumesQuotaRules({ name })
181 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
182
183 const listOwned = (project: string) =>
184 listAtNested(project, "volumes/-", (parent) =>
185 listLabeledPages(
186 netapp.listProjectsLocationsVolumesQuotaRules.pages({
187 parent,
188 pageSize: 1000,
189 }),
190 (page) => page.quotaRules,
191 (item) => item.labels,
192 ),
193 );
194
195 export const VolumesQuotaRuleProvider = () =>
196 Provider.succeed(VolumesQuotaRule, {
197 stables: ["name", "quotaRuleId", "volume", "project", "location", "createTime"],
198
199 diff: Effect.fn(function* ({ news, olds, output }) {
200 if (!isResolved(news)) return undefined;
201 const env = yield* GcpEnvironment.current;
202 const previousType = olds?.type ?? output?.type;
203 const previousTarget = olds?.target ?? output?.target;
204 const nextType = news.type ?? DEFAULT_TYPE;
205 return replaceOnIdentity({
206 previousId: olds?.quotaRuleId ?? output?.quotaRuleId,
207 nextId: news.quotaRuleId ?? olds?.quotaRuleId ?? output?.quotaRuleId,
208 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
209 nextLocation: normalizeLocation(
210 news.location ?? olds?.location ?? output?.location,
211 env.region,
212 ),
213 previousParent: olds?.volume ?? output?.volume,
214 nextParent: news.volume,
215 extra:
216 (previousType !== undefined && nextType !== previousType) ||
217 (previousTarget ?? "") !== (news.target ?? previousTarget ?? ""),
218 });
219 }),
220
221 read: Effect.fn(function* ({ id, olds, output }) {
222 const env = yield* GcpEnvironment.current;
223 const quotaRuleId = yield* toPhysicalId(
224 id,
225 olds?.quotaRuleId,
226 output?.quotaRuleId,
227 "quotarule",
228 );
229 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
230 const parent = olds?.volume ?? output?.volume;
231 // A row whose parent never resolved (failed create) has nothing to read.
232 if (output?.name === undefined && !parent) return undefined;
233 const volume = expandParent(parent ?? "", env.project, location, "volumes");
234 const name = output?.name ?? resourceName(volume, quotaRuleId);
235 const existing = yield* getByName(name);
236 if (existing === undefined) return undefined;
237 const attrs = toAttrs(existing, env.project, env.region);
238 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
239 }),
240
241 list: () =>
242 Effect.gen(function* () {
243 const env = yield* GcpEnvironment.current;
244 const items = yield* listOwned(env.project);
245 return items.map((item) => toAttrs(item, env.project, env.region));
246 }),
247
248 reconcile: Effect.fn(function* ({ id, news, output }) {
249 const env = yield* GcpEnvironment.current;
250 const quotaRuleId = yield* toPhysicalId(
251 id,
252 news.quotaRuleId,
253 output?.quotaRuleId,
254 "quotarule",
255 );
256 const location = normalizeLocation(news.location ?? output?.location, env.region);
257 const volume = expandParent(news.volume, env.project, location, "volumes");
258 const name = resourceName(volume, quotaRuleId);
259 const type = news.type ?? DEFAULT_TYPE;
260 const diskLimitMib = news.diskLimitMib ?? DEFAULT_DISK_LIMIT_MIB;
261 const desiredLabels = {
262 ...toLabels(news.labels),
263 ...(yield* createInternalLabels(id)),
264 };
265
266 let current = yield* getByName(output?.name ?? name);
267
268 if (current === undefined) {
269 const created = yield* netapp
270 .createProjectsLocationsVolumesQuotaRules({
271 parent: volume,
272 quotaRuleId,
273 body: {
274 type,
275 diskLimitMib,
276 target: news.target,
277 description: news.description,
278 labels: desiredLabels,
279 },
280 })
281 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
282 if (created !== undefined) {
283 yield* waitForOperation(created);
284 }
285 current = yield* waitUntilExists(getByName(name), name);
286 }
287
288 if (current === undefined) {
289 return yield* new ResourceNotResolved({ resourceName: name });
290 }
291
292 current = yield* waitUntilReady(
293 getByName(current.name ?? name),
294 current.name ?? name,
295 (item) => item.state,
296 (item) => item.stateDetails,
297 );
298
299 const observedLabels = tagRecord(current.labels);
300 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
301 const mask = fieldMask([
302 (upsert.length > 0 || removed.length > 0) && "labels",
303 (current.description ?? "") !== (news.description ?? "") && "description",
304 (current.diskLimitMib ?? DEFAULT_DISK_LIMIT_MIB) !== diskLimitMib && "diskLimitMib",
305 ]);
306
307 if (mask.length > 0) {
308 const operation = yield* netapp.patchProjectsLocationsVolumesQuotaRules({
309 name: current.name ?? name,
310 updateMask: mask,
311 body: {
312 name: current.name ?? name,
313 labels: desiredLabels,
314 description: news.description,
315 diskLimitMib,
316 },
317 });
318 yield* waitForOperation(operation);
319 current = yield* waitUntilReady(
320 getByName(current.name ?? name),
321 current.name ?? name,
322 (item) => item.state,
323 (item) => item.stateDetails,
324 );
325 }
326
327 return toAttrs(current, env.project, env.region);
328 }),
329
330 delete: Effect.fn(function* ({ output }) {
331 const operation = yield* netapp
332 .deleteProjectsLocationsVolumesQuotaRules({ name: output.name })
333 .pipe(
334 Effect.retry({
335 while: (error) => error._tag === "Conflict",
336 times: 8,
337 schedule: Schedule.spaced("2 seconds"),
338 }),
339 Effect.catchTag("NotFound", () => Effect.undefined),
340 );
341 if (operation !== undefined) {
342 yield* waitForDeleteOperation(operation);
343 }
344 yield* waitUntilGone(getByName(output.name), output.name);
345 }),
346 });