@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 407 lines 13.1 KB
Raw
1 import * as deadline from "@distilled.cloud/aws/deadline";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags, type Tags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as EffectStream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import {
13 asPlain,
14 deadlineArnOf,
15 fetchDeadlineTags,
16 retryWhileFarmSettling,
17 syncDeadlineTags,
18 } from "./internal.ts";
19
20 export class BudgetInvalidProps extends Data.TaggedError("BudgetInvalidProps")<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 export class BudgetUnexpectedResponse extends Data.TaggedError("BudgetUnexpectedResponse")<{
26 readonly message: string;
27 readonly cause?: unknown;
28 }> {}
29
30 export type BudgetStatus = deadline.BudgetStatus;
31 export type BudgetActionType = deadline.BudgetActionType;
32
33 export interface BudgetActionProps {
34 /**
35 * Action taken when the threshold is crossed
36 * (`STOP_SCHEDULING_AND_COMPLETE_TASKS` or
37 * `STOP_SCHEDULING_AND_CANCEL_TASKS`).
38 */
39 type: BudgetActionType;
40 /**
41 * Percentage of the dollar limit at which the action fires (e.g. `100`).
42 */
43 thresholdPercentage: number;
44 /**
45 * A description of the action.
46 */
47 description?: string;
48 }
49
50 export interface BudgetScheduleProps {
51 /**
52 * Fixed budget window.
53 */
54 fixed: {
55 /**
56 * ISO-8601 start of the budget window (e.g. `2026-01-01T00:00:00Z`).
57 */
58 startTime: string;
59 /**
60 * ISO-8601 end of the budget window.
61 */
62 endTime: string;
63 };
64 }
65
66 export interface BudgetProps {
67 /**
68 * The identifier of the farm the budget belongs to. Changing it replaces
69 * the budget.
70 */
71 farmId: string;
72 /**
73 * The identifier of the queue whose usage the budget tracks. Changing it
74 * replaces the budget.
75 */
76 queueId: string;
77 /**
78 * Display name of the budget.
79 * @default ${app}-${stage}-${id}
80 */
81 displayName?: string;
82 /**
83 * A description of the budget.
84 */
85 description?: string;
86 /**
87 * Approximate dollar limit of the budget.
88 */
89 approximateDollarLimit: number;
90 /**
91 * Threshold actions taken as usage approaches the limit.
92 */
93 actions: BudgetActionProps[];
94 /**
95 * The period the budget is measured over.
96 */
97 schedule: BudgetScheduleProps;
98 /**
99 * Whether the budget is evaluated (`ACTIVE`) or ignored (`INACTIVE`).
100 * @default "ACTIVE"
101 */
102 status?: BudgetStatus;
103 /**
104 * Tags to associate with the budget.
105 */
106 tags?: Record<string, string>;
107 }
108
109 export interface Budget extends Resource<
110 "AWS.Deadline.Budget",
111 BudgetProps,
112 {
113 /**
114 * The identifier of the farm the budget belongs to.
115 */
116 farmId: string;
117 /**
118 * Service-assigned unique identifier of the budget (`budget-...`).
119 */
120 budgetId: string;
121 /**
122 * ARN of the budget.
123 */
124 budgetArn: string;
125 /**
126 * The identifier of the queue whose usage the budget tracks.
127 */
128 queueId: string;
129 /**
130 * The budget's display name.
131 */
132 displayName: string;
133 /**
134 * Whether the budget is currently evaluated.
135 */
136 status: BudgetStatus;
137 /**
138 * The configured approximate dollar limit.
139 */
140 approximateDollarLimit: number;
141 /**
142 * Current tags reported for the budget.
143 */
144 tags: Record<string, string>;
145 },
146 never,
147 Providers
148 > {}
149
150 /**
151 * An AWS Deadline Cloud budget — tracks a queue's approximate render spend
152 * over a fixed window and stops scheduling when thresholds are crossed.
153 *
154 * ### Creating Budgets
155 * **Example:** Queue Budget with Hard Stop
156 * ```typescript
157 * import * as AWS from "@alchemy.run/aws";
158 *
159 * const budget = yield* AWS.Deadline.Budget("MonthlyBudget", {
160 * farmId: farm.farmId,
161 * queueId: queue.queueId,
162 * approximateDollarLimit: 100,
163 * actions: [
164 * { type: "STOP_SCHEDULING_AND_COMPLETE_TASKS", thresholdPercentage: 100 },
165 * ],
166 * schedule: {
167 * fixed: {
168 * startTime: "2026-01-01T00:00:00Z",
169 * endTime: "2027-01-01T00:00:00Z",
170 * },
171 * },
172 * });
173 * ```
174 *
175 * **Example:** Graduated Thresholds
176 * ```typescript
177 * // Let in-flight tasks finish at 90%, cancel everything at 100%.
178 * const budget = yield* AWS.Deadline.Budget("QueueBudget", {
179 * farmId: farm.farmId,
180 * queueId: queue.queueId,
181 * approximateDollarLimit: 500,
182 * actions: [
183 * { type: "STOP_SCHEDULING_AND_COMPLETE_TASKS", thresholdPercentage: 90 },
184 * { type: "STOP_SCHEDULING_AND_CANCEL_TASKS", thresholdPercentage: 100 },
185 * ],
186 * schedule: {
187 * fixed: {
188 * startTime: "2026-01-01T00:00:00Z",
189 * endTime: "2026-02-01T00:00:00Z",
190 * },
191 * },
192 * });
193 * ```
194 *
195 * @resource
196 */
197 export const Budget = Resource<Budget>("AWS.Deadline.Budget");
198
199 const createBudgetName = (id: string, props: { displayName?: string | undefined }) =>
200 props.displayName
201 ? Effect.succeed(props.displayName)
202 : createPhysicalName({ id, maxLength: 100 });
203
204 interface BudgetState {
205 attrs: Budget["Attributes"];
206 described: deadline.GetBudgetResponse;
207 }
208
209 const readBudgetById = Effect.fn(function* (
210 farmId: string,
211 budgetId: string,
212 arnOf: (path: string) => string,
213 ) {
214 const described = yield* deadline
215 .getBudget({ farmId, budgetId })
216 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
217 if (!described) return undefined;
218 const budgetArn = arnOf(`farm/${farmId}/budget/${described.budgetId}`);
219 const state: BudgetState = {
220 described,
221 attrs: {
222 farmId,
223 budgetId: described.budgetId,
224 budgetArn,
225 queueId: described.usageTrackingResource.queueId,
226 displayName: described.displayName,
227 status: described.status,
228 approximateDollarLimit: described.approximateDollarLimit,
229 tags: yield* fetchDeadlineTags(budgetArn),
230 },
231 };
232 return state;
233 });
234
235 const findBudgetByDisplayName = Effect.fn(function* (
236 farmId: string,
237 displayName: string,
238 arnOf: (path: string) => string,
239 ) {
240 const summaries = yield* deadline.listBudgets.items({ farmId }).pipe(
241 EffectStream.runCollect,
242 Effect.map((chunk) => Array.from(chunk)),
243 // The parent farm may itself be gone.
244 Effect.catchTag("ResourceNotFoundException", () =>
245 Effect.succeed([] as deadline.BudgetSummary[]),
246 ),
247 );
248 const match = summaries.find((summary) => summary.displayName === displayName);
249 if (!match) return undefined;
250 return yield* readBudgetById(farmId, match.budgetId, arnOf);
251 });
252
253 const actionKey = (action: { type: BudgetActionType; thresholdPercentage: number }) =>
254 `${action.type}@${action.thresholdPercentage}`;
255
256 const toWireSchedule = (schedule: BudgetScheduleProps): deadline.BudgetSchedule => ({
257 fixed: {
258 startTime: new Date(schedule.fixed.startTime),
259 endTime: new Date(schedule.fixed.endTime),
260 },
261 });
262
263 export const BudgetProvider = () =>
264 Provider.effect(
265 Budget,
266 Effect.gen(function* () {
267 return {
268 stables: ["farmId", "budgetId", "budgetArn", "queueId"],
269 // Keyed by a parent farm — sub-resource list() convention.
270 list: () => Effect.succeed([]),
271 read: Effect.fn(function* ({ id, olds, output }) {
272 const arnOf = yield* deadlineArnOf;
273 const farmId = output?.farmId ?? olds?.farmId;
274 if (farmId === undefined) return undefined;
275 const state = output?.budgetId
276 ? yield* readBudgetById(farmId, output.budgetId, arnOf)
277 : yield* findBudgetByDisplayName(
278 farmId,
279 yield* createBudgetName(id, olds ?? {}),
280 arnOf,
281 );
282 if (!state) return undefined;
283 return (yield* hasAlchemyTags(id, state.attrs.tags as Tags))
284 ? state.attrs
285 : Unowned(state.attrs);
286 }),
287 diff: Effect.fn(function* ({ news, olds }) {
288 if (!isResolved(news)) return;
289 if (olds === undefined) return;
290 // The parent farm and tracked queue are fixed at creation.
291 if (olds.farmId !== news.farmId || olds.queueId !== news.queueId) {
292 return { action: "replace" } as const;
293 }
294 }),
295 reconcile: Effect.fn(function* ({ id, news, output, session }) {
296 if (news === undefined) {
297 return yield* new BudgetInvalidProps({ message: "AWS.Deadline.Budget requires props" });
298 }
299 const arnOf = yield* deadlineArnOf;
300 const farmId = news.farmId;
301 const displayName = yield* createBudgetName(id, news);
302 const internalTags = yield* createInternalTags(id);
303 const desiredTags = { ...internalTags, ...news.tags };
304 const desiredSchedule = toWireSchedule(news.schedule);
305
306 // Observe.
307 let state = output?.budgetId
308 ? yield* readBudgetById(farmId, output.budgetId, arnOf)
309 : yield* findBudgetByDisplayName(farmId, displayName, arnOf);
310
311 // Ensure.
312 if (state === undefined) {
313 const created = yield* retryWhileFarmSettling(
314 deadline.createBudget({
315 farmId,
316 displayName,
317 description: news.description,
318 usageTrackingResource: { queueId: news.queueId },
319 approximateDollarLimit: news.approximateDollarLimit,
320 actions: news.actions,
321 schedule: desiredSchedule,
322 tags: desiredTags,
323 }),
324 );
325 yield* session.note(`Created budget ${displayName} (${created.budgetId})`);
326 state = yield* readBudgetById(farmId, created.budgetId, arnOf);
327 if (state === undefined) {
328 return yield* new BudgetUnexpectedResponse({
329 message: `failed to read created budget ${displayName}`,
330 });
331 }
332 }
333
334 // Sync mutable settings — compute action/schedule deltas from
335 // OBSERVED state.
336 const described = state.described;
337 const observedActions = described.actions.map((action) => ({
338 type: action.type,
339 thresholdPercentage: action.thresholdPercentage,
340 }));
341 const observedKeys = new Set(observedActions.map(actionKey));
342 const desiredKeys = new Set(news.actions.map(actionKey));
343 const actionsToAdd = news.actions.filter(
344 (action) => !observedKeys.has(actionKey(action)),
345 );
346 const actionsToRemove = observedActions.filter(
347 (action) => !desiredKeys.has(actionKey(action)),
348 );
349 const observedSchedule = described.schedule.fixed;
350 // Deadline clamps a startTime in the past to the creation instant,
351 // so a past desired startTime can never converge — only compare it
352 // while it is still in the future.
353 const now = yield* Effect.sync(() => Date.now());
354 const desiredStart = desiredSchedule.fixed.startTime.getTime();
355 const scheduleDrifted =
356 (desiredStart > now && observedSchedule.startTime.getTime() !== desiredStart) ||
357 observedSchedule.endTime.getTime() !== desiredSchedule.fixed.endTime.getTime();
358 const desiredStatus = news.status ?? described.status;
359 const needsUpdate =
360 displayName !== described.displayName ||
361 (news.description !== undefined &&
362 news.description !== (asPlain(described.description) ?? "")) ||
363 desiredStatus !== described.status ||
364 news.approximateDollarLimit !== described.approximateDollarLimit ||
365 actionsToAdd.length > 0 ||
366 actionsToRemove.length > 0 ||
367 scheduleDrifted;
368 if (needsUpdate) {
369 yield* retryWhileFarmSettling(
370 deadline.updateBudget({
371 farmId,
372 budgetId: state.attrs.budgetId,
373 displayName,
374 description: news.description,
375 status: news.status,
376 approximateDollarLimit: news.approximateDollarLimit,
377 actionsToAdd: actionsToAdd.length > 0 ? actionsToAdd : undefined,
378 actionsToRemove: actionsToRemove.length > 0 ? actionsToRemove : undefined,
379 schedule: scheduleDrifted ? desiredSchedule : undefined,
380 }),
381 );
382 yield* session.note(`Updated budget ${displayName}`);
383 }
384
385 // Sync tags — diff against observed cloud tags.
386 yield* syncDeadlineTags(state.attrs.budgetArn, desiredTags);
387
388 yield* session.note(state.attrs.budgetArn);
389 const final = yield* readBudgetById(farmId, state.attrs.budgetId, arnOf);
390 if (!final) {
391 return yield* new BudgetUnexpectedResponse({
392 message: `failed to read reconciled budget ${displayName}`,
393 });
394 }
395 return final.attrs;
396 }),
397 delete: Effect.fn(function* ({ output }) {
398 yield* deadline
399 .deleteBudget({
400 farmId: output.farmId,
401 budgetId: output.budgetId,
402 })
403 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
404 }),
405 };
406 }),
407 );