@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, 04:45 UTC

main
ts 226 lines 8.04 KB
Raw
1 import * as mediaconvert from "@distilled.cloud/aws/mediaconvert";
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 } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { readMcTags, syncMcTags } from "./internal.ts";
13
14 export interface QueueProps {
15 /**
16 * Name of the queue. Must be unique within the account/region and match
17 * `^[\w-]+$`. If omitted, a unique name is generated. Changing the name
18 * replaces the queue.
19 */
20 queueName?: string;
21 /**
22 * Optional description of the queue.
23 */
24 description?: string;
25 /**
26 * Pricing plan for the queue. `ON_DEMAND` queues bill per transcode minute;
27 * `RESERVED` queues purchase a reservation (a paid commitment). Changing the
28 * pricing plan replaces the queue.
29 * @default "ON_DEMAND"
30 */
31 pricingPlan?: mediaconvert.PricingPlan;
32 /**
33 * Reservation plan for a `RESERVED` queue (commitment, renewal type, and the
34 * number of reserved render units). Ignored for `ON_DEMAND` queues.
35 */
36 reservationPlanSettings?: mediaconvert.ReservationPlanSettings;
37 /**
38 * Initial/desired queue status. `ACTIVE` queues process jobs; `PAUSED`
39 * queues hold submitted jobs until resumed.
40 * @default "ACTIVE"
41 */
42 status?: mediaconvert.QueueStatus;
43 /**
44 * Maximum number of jobs the queue processes concurrently (ON_DEMAND).
45 */
46 concurrentJobs?: number;
47 /**
48 * User-defined tags for the queue.
49 */
50 tags?: Record<string, string>;
51 }
52
53 export interface Queue extends Resource<
54 "AWS.MediaConvert.Queue",
55 QueueProps,
56 {
57 queueName: string;
58 queueArn: string;
59 type: string | undefined;
60 status: string | undefined;
61 pricingPlan: string | undefined;
62 },
63 never,
64 Providers
65 > {}
66
67 /**
68 * An AWS Elemental MediaConvert queue — the pool that submitted transcode jobs
69 * are scheduled against. Every account has a system `Default` on-demand queue;
70 * create additional queues to isolate workloads or to purchase reserved
71 * render capacity.
72 *
73 * ### Creating a Queue
74 * **Example:** On-Demand Queue
75 * ```typescript
76 * const queue = yield* MediaConvert.Queue("Transcode", {
77 * description: "Marketing video transcodes",
78 * });
79 * ```
80 *
81 * **Example:** Paused Queue
82 * ```typescript
83 * const queue = yield* MediaConvert.Queue("Transcode", {
84 * status: "PAUSED",
85 * tags: { team: "media" },
86 * });
87 * ```
88 *
89 * ### Reserved Capacity
90 * **Example:** Reserved Queue with a One-Year Commitment
91 * ```typescript
92 * const queue = yield* MediaConvert.Queue("Reserved", {
93 * pricingPlan: "RESERVED",
94 * reservationPlanSettings: {
95 * Commitment: "ONE_YEAR",
96 * RenewalType: "EXPIRE",
97 * ReservedSlots: 1,
98 * },
99 * });
100 * ```
101 *
102 * @resource
103 */
104 export const Queue = Resource<Queue>("AWS.MediaConvert.Queue");
105
106 export const QueueProvider = () =>
107 Provider.effect(
108 Queue,
109 Effect.gen(function* () {
110 const createName = Effect.fn(function* (id: string, props: QueueProps) {
111 return props.queueName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
112 });
113
114 const toAttrs = (queue: mediaconvert.Queue & { Name: string }) => ({
115 queueName: queue.Name,
116 queueArn: queue.Arn!,
117 type: queue.Type,
118 status: queue.Status,
119 pricingPlan: queue.PricingPlan,
120 });
121
122 /** Get a queue by name; typed not-found → undefined. */
123 const getQueue = Effect.fn(function* (name: string) {
124 const response = yield* mediaconvert
125 .getQueue({ Name: name })
126 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
127 return response?.Queue;
128 });
129
130 return {
131 stables: ["queueName", "queueArn"],
132
133 diff: Effect.fn(function* ({ id, olds, news }) {
134 if (!isResolved(news)) return undefined;
135 const oldName = yield* createName(id, olds);
136 const newName = yield* createName(id, news);
137 // The name is the queue's identity; a change means a new queue.
138 if (oldName !== newName) return { action: "replace" } as const;
139 // Pricing plan is immutable once the queue exists.
140 if ((olds.pricingPlan ?? "ON_DEMAND") !== (news.pricingPlan ?? "ON_DEMAND")) {
141 return { action: "replace" } as const;
142 }
143 }),
144
145 read: Effect.fn(function* ({ id, olds, output }) {
146 const name = output?.queueName ?? (yield* createName(id, olds ?? {}));
147 const queue = yield* getQueue(name);
148 if (queue === undefined) return undefined;
149 const attrs = toAttrs(queue);
150 const tags = yield* readMcTags(queue.Arn!);
151 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
152 }),
153
154 reconcile: Effect.fn(function* ({ id, news, output, session }) {
155 const internalTags = yield* createInternalTags(id);
156 const desiredTags = { ...internalTags, ...news.tags };
157 const name = output?.queueName ?? (yield* createName(id, news));
158
159 // 1. Observe — cloud state is authoritative; output is an id cache.
160 let queue = yield* getQueue(name);
161
162 // 2. Ensure — create if missing.
163 if (queue === undefined) {
164 const created = yield* mediaconvert.createQueue({
165 Name: name,
166 Description: news.description,
167 PricingPlan: news.pricingPlan,
168 ReservationPlanSettings: news.reservationPlanSettings,
169 Status: news.status,
170 ConcurrentJobs: news.concurrentJobs,
171 Tags: desiredTags,
172 });
173 queue = created.Queue!;
174 } else {
175 // 3. Sync — MediaConvert's UpdateQueue is a full in-place update of
176 // the mutable fields. Apply whenever any of them drift.
177 const statusDrift = (news.status ?? "ACTIVE") !== (queue.Status ?? "ACTIVE");
178 const descDrift = (news.description ?? undefined) !== (queue.Description ?? undefined);
179 const concurrencyDrift =
180 news.concurrentJobs !== undefined && news.concurrentJobs !== queue.ConcurrentJobs;
181 if (statusDrift || descDrift || concurrencyDrift) {
182 const updated = yield* mediaconvert.updateQueue({
183 Name: name,
184 Description: news.description,
185 Status: news.status,
186 ConcurrentJobs: news.concurrentJobs,
187 ReservationPlanSettings: news.reservationPlanSettings,
188 });
189 queue = updated.Queue!;
190 }
191 }
192
193 // 3b. Sync tags — diff against OBSERVED cloud tags.
194 yield* syncMcTags(queue.Arn!, desiredTags);
195
196 yield* session.note(name);
197 return toAttrs(queue as mediaconvert.Queue & { Name: string });
198 }),
199
200 delete: Effect.fn(function* ({ output }) {
201 yield* mediaconvert.deleteQueue({ Name: output.queueName }).pipe(
202 Effect.catchTag("NotFoundException", () => Effect.void),
203 // A queue draining in-flight jobs can transiently reject deletion.
204 Effect.retry({
205 while: (e) => e._tag === "ConflictException",
206 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
207 }),
208 );
209 }),
210
211 list: () =>
212 mediaconvert.listQueues.pages({}).pipe(
213 Stream.runCollect,
214 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Queues ?? [])),
215 Effect.map((queues) =>
216 queues
217 // The built-in `Default` queue is an AWS SYSTEM queue that
218 // always exists and can never be deleted — keep it out of
219 // enumeration for account-wide teardown (nuke).
220 .filter((q) => q.Type !== "SYSTEM")
221 .map(toAttrs),
222 ),
223 ),
224 };
225 }),
226 );