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

main
ts 289 lines 9.84 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 reapDeadlineLogGroups,
17 reapFarmChildren,
18 retryWhileConflict,
19 syncDeadlineTags,
20 } from "./internal.ts";
21
22 export class FarmInvalidProps extends Data.TaggedError("FarmInvalidProps")<{
23 readonly message: string;
24 readonly cause?: unknown;
25 }> {}
26
27 export class FarmUnexpectedResponse extends Data.TaggedError("FarmUnexpectedResponse")<{
28 readonly message: string;
29 readonly cause?: unknown;
30 }> {}
31
32 export interface FarmProps {
33 /**
34 * Display name of the farm.
35 * @default ${app}-${stage}-${id}
36 */
37 displayName?: string;
38 /**
39 * A description of the farm.
40 */
41 description?: string;
42 /**
43 * ARN of the KMS key used to encrypt farm data. Changing it replaces the
44 * farm.
45 * @default an AWS-owned key
46 */
47 kmsKeyArn?: string;
48 /**
49 * Multiplier applied to the cost of renders on this farm when computing
50 * budget usage.
51 * @default 1
52 */
53 costScaleFactor?: number;
54 /**
55 * Tags to associate with the farm.
56 */
57 tags?: Record<string, string>;
58 }
59
60 export interface Farm extends Resource<
61 "AWS.Deadline.Farm",
62 FarmProps,
63 {
64 /**
65 * Service-assigned unique identifier of the farm (`farm-...`).
66 */
67 farmId: string;
68 /**
69 * ARN of the farm.
70 */
71 farmArn: string;
72 /**
73 * The farm's display name.
74 */
75 displayName: string;
76 /**
77 * ARN of the KMS key encrypting farm data, when customer-managed.
78 */
79 kmsKeyArn: string | undefined;
80 /**
81 * The configured cost scale factor.
82 */
83 costScaleFactor: number;
84 /**
85 * Current tags reported for the farm.
86 */
87 tags: Record<string, string>;
88 },
89 never,
90 Providers
91 > {}
92
93 /**
94 * An AWS Deadline Cloud farm — the top-level container for render-farm
95 * queues, fleets, storage profiles, and budgets.
96 *
97 * ### Creating Farms
98 * **Example:** Basic Farm
99 * ```typescript
100 * import * as AWS from "@alchemy.run/aws";
101 *
102 * const farm = yield* AWS.Deadline.Farm("RenderFarm", {});
103 * ```
104 *
105 * **Example:** Farm with Description and Cost Scaling
106 * ```typescript
107 * const farm = yield* AWS.Deadline.Farm("RenderFarm", {
108 * displayName: "studio-renders",
109 * description: "Production render farm",
110 * costScaleFactor: 1.5,
111 * tags: { team: "vfx" },
112 * });
113 * ```
114 *
115 * @resource
116 */
117 export const Farm = Resource<Farm>("AWS.Deadline.Farm");
118
119 const createFarmName = (id: string, props: { displayName?: string | undefined }) =>
120 props.displayName
121 ? Effect.succeed(props.displayName)
122 : createPhysicalName({ id, maxLength: 100 });
123
124 interface FarmState {
125 attrs: Farm["Attributes"];
126 described: deadline.GetFarmResponse;
127 }
128
129 const readFarmById = Effect.fn(function* (farmId: string, arnOf: (path: string) => string) {
130 const described = yield* deadline
131 .getFarm({ farmId })
132 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
133 if (!described) return undefined;
134 const farmArn = arnOf(`farm/${described.farmId}`);
135 const state: FarmState = {
136 described,
137 attrs: {
138 farmId: described.farmId,
139 farmArn,
140 displayName: described.displayName,
141 kmsKeyArn: described.kmsKeyArn,
142 costScaleFactor: described.costScaleFactor,
143 tags: yield* fetchDeadlineTags(farmArn),
144 },
145 };
146 return state;
147 });
148
149 const findFarmByDisplayName = Effect.fn(function* (
150 displayName: string,
151 arnOf: (path: string) => string,
152 ) {
153 const summaries = yield* deadline.listFarms.items({}).pipe(
154 EffectStream.runCollect,
155 Effect.map((chunk) => Array.from(chunk)),
156 );
157 const match = summaries.find((summary) => summary.displayName === displayName);
158 if (!match) return undefined;
159 return yield* readFarmById(match.farmId, arnOf);
160 });
161
162 export const FarmProvider = () =>
163 Provider.effect(
164 Farm,
165 Effect.gen(function* () {
166 return {
167 stables: ["farmId", "farmArn"],
168 list: () =>
169 Effect.gen(function* () {
170 const arnOf = yield* deadlineArnOf;
171 const summaries = yield* deadline.listFarms.items({}).pipe(
172 EffectStream.runCollect,
173 Effect.map((chunk) => Array.from(chunk)),
174 );
175 const states = yield* Effect.forEach(
176 summaries,
177 (summary) => readFarmById(summary.farmId, arnOf),
178 { concurrency: 4 },
179 );
180 return states
181 .filter((state): state is FarmState => state !== undefined)
182 .map((state) => state.attrs);
183 }),
184 read: Effect.fn(function* ({ id, olds, output }) {
185 const arnOf = yield* deadlineArnOf;
186 const state = output?.farmId
187 ? yield* readFarmById(output.farmId, arnOf)
188 : yield* findFarmByDisplayName(yield* createFarmName(id, olds ?? {}), arnOf);
189 if (!state) return undefined;
190 return (yield* hasAlchemyTags(id, state.attrs.tags as Tags))
191 ? state.attrs
192 : Unowned(state.attrs);
193 }),
194 diff: Effect.fn(function* ({ news, olds }) {
195 if (!isResolved(news)) return;
196 if (olds === undefined) return;
197 // The KMS key is fixed at creation.
198 if ((olds.kmsKeyArn ?? undefined) !== (news.kmsKeyArn ?? undefined)) {
199 return { action: "replace" } as const;
200 }
201 }),
202 reconcile: Effect.fn(function* ({ id, news, output, session }) {
203 if (news === undefined) {
204 return yield* new FarmInvalidProps({ message: "AWS.Deadline.Farm requires props" });
205 }
206 const arnOf = yield* deadlineArnOf;
207 const displayName = yield* createFarmName(id, news);
208 const internalTags = yield* createInternalTags(id);
209 const desiredTags = { ...internalTags, ...news.tags };
210
211 // Observe — prefer the cached farmId; fall back to a display-name
212 // lookup so a create whose state failed to persist is adopted.
213 let state = output?.farmId
214 ? yield* readFarmById(output.farmId, arnOf)
215 : yield* findFarmByDisplayName(displayName, arnOf);
216
217 // Ensure — create if missing.
218 if (state === undefined) {
219 const created = yield* deadline.createFarm({
220 displayName,
221 description: news.description,
222 kmsKeyArn: news.kmsKeyArn,
223 costScaleFactor: news.costScaleFactor,
224 tags: desiredTags,
225 });
226 yield* session.note(`Created farm ${displayName} (${created.farmId})`);
227 state = yield* readFarmById(created.farmId, arnOf);
228 if (state === undefined) {
229 return yield* new FarmUnexpectedResponse({
230 message: `failed to read created farm ${displayName}`,
231 });
232 }
233 }
234
235 // Sync mutable settings — only when drifted from OBSERVED state.
236 const described = state.described;
237 const needsUpdate =
238 displayName !== described.displayName ||
239 (news.description !== undefined &&
240 news.description !== (asPlain(described.description) ?? "")) ||
241 (news.costScaleFactor !== undefined &&
242 news.costScaleFactor !== described.costScaleFactor);
243 if (needsUpdate) {
244 yield* deadline.updateFarm({
245 farmId: state.attrs.farmId,
246 displayName,
247 description: news.description,
248 costScaleFactor: news.costScaleFactor,
249 });
250 yield* session.note(`Updated farm ${displayName}`);
251 }
252
253 // Sync tags — diff against observed cloud tags.
254 yield* syncDeadlineTags(state.attrs.farmArn, desiredTags);
255
256 yield* session.note(state.attrs.farmArn);
257 const final = yield* readFarmById(state.attrs.farmId, arnOf);
258 if (!final) {
259 return yield* new FarmUnexpectedResponse({
260 message: `failed to read reconciled farm ${displayName}`,
261 });
262 }
263 return final.attrs;
264 }),
265 delete: Effect.fn(function* ({ output }) {
266 // A farm refuses deletion while ANY child resource exists (storage
267 // profiles, queues, fleets, budgets, limits, associations) — and
268 // unlike async sub-resource drain, those conflicts never resolve
269 // by waiting. A normal stack destroy deletes children first, so
270 // this reap observes nothing; an orphan sweep (nuke) or a mid-run
271 // crash targets a farm whose children were never enumerated, and
272 // without the reap deleteFarm conflicts until the retry budget
273 // runs out and the farm leaks.
274 yield* reapFarmChildren(output.farmId);
275 // Child deletion (queues, fleets) finishes asynchronously; the
276 // farm rejects deletion with ConflictException until it settles.
277 yield* retryWhileConflict(deadline.deleteFarm({ farmId: output.farmId })).pipe(
278 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
279 );
280 // Deadline auto-creates log groups under /aws/deadline/{farmId}/
281 // (queue job/session logs, fleet worker logs) and deleteFarm does
282 // NOT remove them. The farm only deletes once every sub-resource
283 // is fully gone, so by this point all of its log groups exist if
284 // they ever will — sweep the whole prefix.
285 yield* reapDeadlineLogGroups(`/aws/deadline/${output.farmId}`);
286 }),
287 };
288 }),
289 );