@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 373 lines 13.9 KB
Raw
1 import * as servicequotas from "@distilled.cloud/aws/service-quotas";
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 Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9
10 export interface ServiceQuotaIncreaseRequestProps {
11 /**
12 * Service identifier the quota belongs to, e.g. `"vpc"`, `"lambda"`,
13 * `"ec2"`. Discover codes with `servicequotas.listServices`.
14 * Changing this replaces the resource.
15 */
16 serviceCode: string;
17 /**
18 * Quota identifier, e.g. `"L-F678F1CE"` (VPCs per region).
19 * Discover codes with `servicequotas.listServiceQuotas`.
20 * Changing this replaces the resource.
21 */
22 quotaCode: string;
23 /**
24 * The new quota value to request. Must be greater than the currently
25 * applied value. If the applied quota already meets or exceeds this value
26 * no request is submitted. Raising it later submits a new request.
27 */
28 desiredValue: number;
29 /**
30 * Resource context for resource-level quotas (e.g. an EC2 instance family
31 * or an OpenSearch domain ARN). Omit for account-level quotas.
32 * Changing this replaces the resource.
33 */
34 contextId?: string;
35 /**
36 * Whether AWS may open a support case for the request when it cannot be
37 * auto-approved.
38 * @default AWS decides (a case is opened when required)
39 */
40 supportCaseAllowed?: boolean;
41 }
42
43 export interface ServiceQuotaIncreaseRequest extends Resource<
44 "AWS.ServiceQuotas.ServiceQuotaIncreaseRequest",
45 ServiceQuotaIncreaseRequestProps,
46 {
47 /**
48 * ID of the quota increase request. Undefined when the applied quota
49 * already met the desired value and no request was needed.
50 */
51 requestId: string | undefined;
52 /**
53 * Request status: `PENDING`, `CASE_OPENED`, `APPROVED`, `DENIED`,
54 * `CASE_CLOSED`, `NOT_APPROVED` or `INVALID_REQUEST`. Undefined when no
55 * request was needed.
56 */
57 status: string | undefined;
58 /** Support case ID, when the request opened a case. */
59 caseId: string | undefined;
60 /** Service identifier the quota belongs to. */
61 serviceCode: string;
62 /** Quota identifier. */
63 quotaCode: string;
64 /** The requested (desired) quota value. */
65 desiredValue: number;
66 /**
67 * The applied quota value observed at last reconcile (the AWS default
68 * value when no account override is applied).
69 */
70 appliedValue: number | undefined;
71 /** ARN of the quota. */
72 quotaArn: string | undefined;
73 /** Human-readable quota name. */
74 quotaName: string | undefined;
75 /** Human-readable service name. */
76 serviceName: string | undefined;
77 /** Unit of measurement of the quota value. */
78 unit: string | undefined;
79 /** Whether the quota is global (not region-scoped). */
80 globalQuota: boolean | undefined;
81 },
82 never,
83 Providers
84 > {}
85
86 /**
87 * A Service Quotas quota increase request at the account or resource level.
88 *
89 * :::caution
90 * Submitting a quota increase request may open an AWS Support case and
91 * **cannot be cancelled through the Service Quotas API**. Destroying this
92 * resource only forgets the request — a still-open request (and its support
93 * case, if any) lives on in AWS.
94 * :::
95 *
96 * The reconciler is idempotent: it first observes the applied quota value
97 * and any open request for the quota. A new request is submitted only when
98 * the applied value is below `desiredValue` and no open request already
99 * asks for it. Raising `desiredValue` later submits a new request.
100 *
101 * ### Requesting a Quota Increase
102 * **Example:** Raise the VPCs-per-region quota
103 * ```typescript
104 * const increase = yield* ServiceQuotas.ServiceQuotaIncreaseRequest("MoreVpcs", {
105 * serviceCode: "vpc",
106 * quotaCode: "L-F678F1CE",
107 * desiredValue: 10,
108 * });
109 * ```
110 *
111 * **Example:** Request without allowing a support case
112 * ```typescript
113 * const increase = yield* ServiceQuotas.ServiceQuotaIncreaseRequest("MoreFunctions", {
114 * serviceCode: "lambda",
115 * quotaCode: "L-B99A9384",
116 * desiredValue: 2000,
117 * supportCaseAllowed: false,
118 * });
119 * ```
120 */
121 export const ServiceQuotaIncreaseRequest = Resource<ServiceQuotaIncreaseRequest>(
122 "AWS.ServiceQuotas.ServiceQuotaIncreaseRequest",
123 );
124
125 // Statuses in which a request is still in flight and represents the desired
126 // state (a new submission would be rejected with ResourceAlreadyExists).
127 const OPEN_STATUSES = ["PENDING", "CASE_OPENED"] as const;
128
129 // Read a request by ID; a typed NoSuchResourceException collapses to
130 // undefined (requests eventually age out of the 90-day history).
131 const getRequest = (requestId: string) =>
132 servicequotas.getRequestedServiceQuotaChange({ RequestId: requestId }).pipe(
133 Effect.map((r) => r.RequestedQuota),
134 Effect.catchTag("NoSuchResourceException", () => Effect.undefined),
135 );
136
137 // Observe the applied quota value; quotas without an applied (account-level)
138 // value fall back to the AWS default value.
139 const observeQuota = (serviceCode: string, quotaCode: string, contextId: string | undefined) =>
140 servicequotas
141 .getServiceQuota({
142 ServiceCode: serviceCode,
143 QuotaCode: quotaCode,
144 ContextId: contextId,
145 })
146 .pipe(
147 Effect.map((r) => r.Quota),
148 Effect.catchTag("NoSuchResourceException", () =>
149 servicequotas
150 .getAWSDefaultServiceQuota({
151 ServiceCode: serviceCode,
152 QuotaCode: quotaCode,
153 })
154 .pipe(
155 Effect.map((r) => r.Quota),
156 Effect.catchTag("NoSuchResourceException", () => Effect.undefined),
157 ),
158 ),
159 );
160
161 // Find an open (PENDING / CASE_OPENED) increase request for the quota,
162 // optionally constrained to an exact desired value.
163 const findOpenRequest = Effect.fn(function* (
164 serviceCode: string,
165 quotaCode: string,
166 desiredValue?: number,
167 ) {
168 for (const status of OPEN_STATUSES) {
169 const page = yield* servicequotas
170 .listRequestedServiceQuotaChangeHistoryByQuota({
171 ServiceCode: serviceCode,
172 QuotaCode: quotaCode,
173 Status: status,
174 })
175 .pipe(
176 Effect.map((r) => r.RequestedQuotas ?? []),
177 Effect.catchTag("NoSuchResourceException", () =>
178 Effect.succeed([] as servicequotas.RequestedServiceQuotaChange[]),
179 ),
180 );
181 const match = page.find((r) => desiredValue === undefined || r.DesiredValue === desiredValue);
182 if (match !== undefined) return match;
183 }
184 return undefined;
185 });
186
187 const buildAttrs = (
188 identity: { serviceCode: string; quotaCode: string; desiredValue: number },
189 request: servicequotas.RequestedServiceQuotaChange | undefined,
190 quota: servicequotas.ServiceQuota | undefined,
191 ) => ({
192 requestId: request?.Id,
193 status: request?.Status,
194 caseId: request?.CaseId,
195 serviceCode: identity.serviceCode,
196 quotaCode: identity.quotaCode,
197 desiredValue: request?.DesiredValue ?? identity.desiredValue,
198 appliedValue: quota?.Value,
199 quotaArn: request?.QuotaArn ?? quota?.QuotaArn,
200 quotaName: request?.QuotaName ?? quota?.QuotaName,
201 serviceName: request?.ServiceName ?? quota?.ServiceName,
202 unit: request?.Unit ?? quota?.Unit,
203 globalQuota: request?.GlobalQuota ?? quota?.GlobalQuota,
204 });
205
206 export const ServiceQuotaIncreaseRequestProvider = () =>
207 Provider.effect(
208 ServiceQuotaIncreaseRequest,
209 Effect.gen(function* () {
210 return {
211 stables: [
212 "serviceCode",
213 "quotaCode",
214 "quotaArn",
215 "quotaName",
216 "serviceName",
217 "unit",
218 "globalQuota",
219 ],
220
221 // Top-level enumeration: every quota increase request in the
222 // account's 90-day request history.
223 list: () =>
224 servicequotas.listRequestedServiceQuotaChangeHistory.pages({}).pipe(
225 Stream.runCollect,
226 Effect.map((chunk) =>
227 Array.from(chunk)
228 .flatMap((page) => page.RequestedQuotas ?? [])
229 .flatMap((request) =>
230 request.Id !== undefined
231 ? [
232 buildAttrs(
233 {
234 serviceCode: request.ServiceCode ?? "",
235 quotaCode: request.QuotaCode ?? "",
236 desiredValue: request.DesiredValue ?? 0,
237 },
238 request,
239 undefined,
240 ),
241 ]
242 : [],
243 ),
244 ),
245 ),
246
247 read: Effect.fn(function* ({ olds, output }) {
248 const serviceCode = output?.serviceCode ?? olds?.serviceCode;
249 const quotaCode = output?.quotaCode ?? olds?.quotaCode;
250 const desiredValue = output?.desiredValue ?? olds?.desiredValue;
251 if (serviceCode === undefined || quotaCode === undefined) {
252 return undefined;
253 }
254 const quota = yield* observeQuota(serviceCode, quotaCode, olds?.contextId);
255 let request =
256 output?.requestId !== undefined ? yield* getRequest(output.requestId) : undefined;
257 if (request === undefined) {
258 request = yield* findOpenRequest(serviceCode, quotaCode, desiredValue);
259 }
260 if (request !== undefined) {
261 const attrs = buildAttrs(
262 {
263 serviceCode,
264 quotaCode,
265 desiredValue: request.DesiredValue ?? desiredValue ?? 0,
266 },
267 request,
268 quota,
269 );
270 // Requests are not taggable, so ownership cannot be verified
271 // from cloud state alone. An open request discovered without
272 // prior state is gated behind --adopt.
273 return output !== undefined ? attrs : Unowned(attrs);
274 }
275 // No request on record. When WE previously reconciled this
276 // resource (output present) and the applied quota still satisfies
277 // the desired value, the resource is intact. Without prior state
278 // a merely-satisfied quota is NOT a pre-existing foreign resource
279 // (there is nothing to adopt) — report it as missing.
280 if (
281 output !== undefined &&
282 desiredValue !== undefined &&
283 quota?.Value !== undefined &&
284 quota.Value >= desiredValue
285 ) {
286 return buildAttrs({ serviceCode, quotaCode, desiredValue }, undefined, quota);
287 }
288 return undefined;
289 }),
290
291 diff: Effect.fn(function* ({ news, olds }) {
292 if (!isResolved(news)) return undefined;
293 if (
294 news.serviceCode !== olds.serviceCode ||
295 news.quotaCode !== olds.quotaCode ||
296 news.contextId !== olds.contextId
297 ) {
298 return { action: "replace" } as const;
299 }
300 // desiredValue / supportCaseAllowed changes fall through to the
301 // default update path — reconcile submits a new request if needed.
302 }),
303
304 reconcile: Effect.fn(function* ({ news, output, session }) {
305 const { serviceCode, quotaCode, desiredValue } = news;
306
307 // 1. OBSERVE — the applied quota value and any existing request.
308 // Cloud state is authoritative; output only caches the request
309 // ID from a previous run.
310 const quota = yield* observeQuota(serviceCode, quotaCode, news.contextId);
311 let request =
312 output?.requestId !== undefined ? yield* getRequest(output.requestId) : undefined;
313 if (
314 request !== undefined &&
315 (request.ServiceCode !== serviceCode ||
316 request.QuotaCode !== quotaCode ||
317 request.DesiredValue !== desiredValue)
318 ) {
319 // The cached request no longer reflects the desired state.
320 request = undefined;
321 }
322 if (request === undefined) {
323 request = yield* findOpenRequest(serviceCode, quotaCode, desiredValue);
324 }
325
326 // 2. ENSURE — submit only when the applied value is below the
327 // desired value and no matching request is already in flight.
328 if (request === undefined) {
329 const satisfied = quota?.Value !== undefined && quota.Value >= desiredValue;
330 if (!satisfied) {
331 request = yield* servicequotas
332 .requestServiceQuotaIncrease({
333 ServiceCode: serviceCode,
334 QuotaCode: quotaCode,
335 DesiredValue: desiredValue,
336 ContextId: news.contextId,
337 SupportCaseAllowed: news.supportCaseAllowed,
338 })
339 .pipe(
340 Effect.map((r) => r.RequestedQuota),
341 // An open request for this quota already exists (created
342 // out-of-band, or a race with a prior partial run) —
343 // converge on it instead of failing.
344 Effect.catchTag("ResourceAlreadyExistsException", () =>
345 findOpenRequest(serviceCode, quotaCode),
346 ),
347 );
348 }
349 }
350
351 // 3. A submitted request is immutable — nothing further to sync.
352 if (request?.Id !== undefined) {
353 yield* session.note(request.Id);
354 }
355 return buildAttrs({ serviceCode, quotaCode, desiredValue }, request, quota);
356 }),
357
358 delete: Effect.fn(function* ({ output }) {
359 // Service Quotas offers no API to cancel a submitted quota
360 // increase request. Deleting the resource only forgets it; a
361 // still-open request (and its support case) remains in AWS.
362 if (
363 output.requestId !== undefined &&
364 (output.status === "PENDING" || output.status === "CASE_OPENED")
365 ) {
366 yield* Effect.logWarning(
367 `Quota increase request ${output.requestId} for ${output.serviceCode}/${output.quotaCode} is still open and cannot be cancelled via the Service Quotas API; it remains in AWS.`,
368 );
369 }
370 }),
371 };
372 }),
373 );