@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 290 lines 9.52 KB
Raw
1 import * as transcoder from "@distilled.cloud/gcp/transcoder_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 * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 configKey,
12 desiredLabelsOf,
13 getJobTemplate,
14 JobTemplateNotResolved,
15 JobTemplateStillExists,
16 labelsKey,
17 listOwnedJobTemplates,
18 locationParent,
19 normalizeLocation,
20 ownedByAlchemy,
21 parseName,
22 resourceName,
23 toJobTemplateId,
24 userLabels,
25 waitUntilExists,
26 waitUntilGone,
27 } from "./internal.ts";
28
29 export type JobConfig = transcoder.JobConfig;
30 export type ElementaryStream = transcoder.ElementaryStream;
31 export type MuxStream = transcoder.MuxStream;
32 export type AudioStream = transcoder.AudioStream;
33 export type VideoStream = transcoder.VideoStream;
34
35 export type JobTemplateProps = {
36 /**
37 * Job template id (the `{job_template}` segment of
38 * `projects/{project}/locations/{location}/jobTemplates/{job_template}`).
39 * If omitted, a unique name is generated from the stack, stage, and
40 * logical id. 4-63 characters matching `[a-zA-Z][a-zA-Z0-9_-]*`.
41 * Immutable — changing it replaces the template.
42 */
43 jobTemplateId?: string;
44 /**
45 * Transcoder location (`us-central1`, `us-east1`, …). Immutable —
46 * changing it replaces the template. `US-CENTRAL1` is accepted and
47 * normalized to `us-central1`.
48 * @default the stack's GCP region (`GCP.Region`, else the profile
49 * region, else `us-central1`)
50 */
51 location?: string;
52 /**
53 * Transcoding configuration (elementary streams, mux streams, inputs,
54 * outputs, manifests, …). The Transcoder API has no update method, so
55 * changing `config` replaces the template.
56 */
57 config: JobConfig;
58 /**
59 * User labels. Alchemy ownership labels are merged in automatically.
60 * The API has no update method, so changing labels replaces the
61 * template.
62 */
63 labels?: Record<string, string>;
64 };
65
66 export type JobTemplate = Resource<
67 "GCP.Transcoder.JobTemplate",
68 JobTemplateProps,
69 {
70 /** Full resource name `projects/{project}/locations/{location}/jobTemplates/{job_template}`. */
71 name: string;
72 /** Job template id (last path segment). */
73 jobTemplateId: string;
74 /** Location id (`us-central1`, …). */
75 location: string;
76 /** Project id. */
77 project: string;
78 /** Parent `projects/{project}/locations/{location}`. */
79 parent: string;
80 /** Transcoding configuration stored on the template. */
81 config: JobConfig | undefined;
82 /** User labels (Alchemy ownership labels stripped). */
83 labels: Record<string, string>;
84 },
85 never,
86 Providers
87 >;
88
89 /**
90 * A Transcoder API job template. Templates capture a reusable
91 * `JobConfig` so jobs can be created with `templateId` instead of
92 * repeating elementary/mux stream settings.
93 *
94 * The API exposes create, get, list, and delete only — there is no
95 * patch. Changing `jobTemplateId`, `location`, `config`, or `labels`
96 * replaces the template. Ownership is stamped with Alchemy labels so
97 * `list` / nuke can find it.
98 *
99 * ### Creating a Job Template
100 * **Example:** Generated id
101 * ```typescript
102 * const template = yield* GCP.Transcoder.JobTemplate("WebHd", {
103 * config: {
104 * elementaryStreams: [
105 * {
106 * key: "video-stream0",
107 * videoStream: {
108 * h264: {
109 * heightPixels: 360,
110 * widthPixels: 640,
111 * bitrateBps: 550000,
112 * frameRate: 30,
113 * },
114 * },
115 * },
116 * {
117 * key: "audio-stream0",
118 * audioStream: { codec: "aac", bitrateBps: 64000 },
119 * },
120 * ],
121 * muxStreams: [
122 * {
123 * key: "sd",
124 * container: "mp4",
125 * elementaryStreams: ["video-stream0", "audio-stream0"],
126 * },
127 * ],
128 * },
129 * });
130 * ```
131 *
132 * **Example:** Explicit id and labels
133 * ```typescript
134 * const template = yield* GCP.Transcoder.JobTemplate("WebHd", {
135 * jobTemplateId: "web-sd",
136 * location: "us-central1",
137 * labels: { env: "prod" },
138 * config: {
139 * elementaryStreams: [
140 * {
141 * key: "video-stream0",
142 * videoStream: {
143 * h264: { bitrateBps: 550000, frameRate: 30 },
144 * },
145 * },
146 * ],
147 * muxStreams: [
148 * {
149 * key: "sd",
150 * container: "mp4",
151 * elementaryStreams: ["video-stream0"],
152 * },
153 * ],
154 * },
155 * });
156 * ```
157 *
158 * ### Creating a Job from a Template
159 * **Example:** Start a transcode
160 * ```typescript
161 * const createJob = yield* GCP.Transcoder.CreateJob(template);
162 * const job = yield* createJob({
163 * body: {
164 * inputUri: "gs://bucket/inputs/file.mp4",
165 * outputUri: "gs://bucket/outputs/",
166 * },
167 * });
168 * ```
169 *
170 * @resource
171 * @category Transcoder
172 */
173 export const JobTemplate = Resource<JobTemplate>("GCP.Transcoder.JobTemplate");
174
175 export { JobTemplateNotResolved, JobTemplateStillExists };
176
177 const toAttrs = (template: transcoder.JobTemplate, project: string, region: string) => {
178 const name = template.name ?? "";
179 const parsed = parseName(name, region);
180 return {
181 name,
182 jobTemplateId: parsed.jobTemplateId,
183 location: parsed.location,
184 project: parsed.project || project,
185 parent: parsed.parent || locationParent(project, parsed.location),
186 config: template.config,
187 labels: userLabels(template.labels),
188 };
189 };
190
191 export const JobTemplateProvider = () =>
192 Provider.succeed(JobTemplate, {
193 stables: ["name", "jobTemplateId", "location", "project", "parent"],
194
195 diff: Effect.fn(function* ({ news, olds, output }) {
196 if (!isResolved(news)) return undefined;
197 const env = yield* GcpEnvironment.current;
198 const previousId = olds?.jobTemplateId ?? output?.jobTemplateId;
199 const nextId = news.jobTemplateId ?? previousId;
200 const idChanged = previousId !== undefined && nextId !== undefined && previousId !== nextId;
201 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
202 const nextLocation = normalizeLocation(
203 news.location ?? olds?.location ?? output?.location,
204 env.region,
205 );
206 const locationChanged = previousLocation !== nextLocation;
207 const configChanged = olds !== undefined && configKey(news.config) !== configKey(olds.config);
208 const labelsChanged = olds !== undefined && labelsKey(news.labels) !== labelsKey(olds.labels);
209 if (!idChanged && !locationChanged && !configChanged && !labelsChanged) {
210 return undefined;
211 }
212 return {
213 action: "replace" as const,
214 deleteFirst: !idChanged && !locationChanged,
215 };
216 }),
217
218 read: Effect.fn(function* ({ id, olds, output }) {
219 const env = yield* GcpEnvironment.current;
220 const jobTemplateId = yield* toJobTemplateId(id, olds?.jobTemplateId, output?.jobTemplateId);
221 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
222 const name = output?.name ?? resourceName(env.project, location, jobTemplateId);
223 const existing = yield* getJobTemplate(name);
224 if (existing === undefined) return undefined;
225 const attrs = toAttrs(existing, env.project, env.region);
226 return (yield* ownedByAlchemy(id, existing.labels)) ? attrs : Unowned(attrs);
227 }),
228
229 list: () =>
230 Effect.gen(function* () {
231 const env = yield* GcpEnvironment.current;
232 const rows = yield* listOwnedJobTemplates(env.project, env.region);
233 return rows.map((row) => toAttrs(row, env.project, env.region));
234 }),
235
236 reconcile: Effect.fn(function* ({ id, news, output }) {
237 const env = yield* GcpEnvironment.current;
238 const jobTemplateId = yield* toJobTemplateId(id, news.jobTemplateId, output?.jobTemplateId);
239 const location = normalizeLocation(news.location ?? output?.location, env.region);
240 const parent = locationParent(env.project, location);
241 const name = resourceName(env.project, location, jobTemplateId);
242 const desiredLabels = yield* desiredLabelsOf(id, news.labels);
243
244 let current = yield* getJobTemplate(name);
245
246 if (current === undefined) {
247 const created = yield* transcoder
248 .createProjectsLocationsJobTemplates({
249 parent,
250 jobTemplateId,
251 body: {
252 name,
253 config: news.config,
254 labels: desiredLabels,
255 },
256 })
257 // ALREADY_EXISTS proves the template exists (a lost race, or a
258 // retried create whose first attempt landed) — wait for it to
259 // become readable instead of failing, so the attempt converges
260 // rather than leaving an untracked template behind.
261 .pipe(Effect.catchTag("Conflict", () => waitUntilExists(name)));
262 current = created ?? undefined;
263 }
264
265 if (current === undefined) {
266 return yield* new JobTemplateNotResolved({
267 resourceName: output?.name ?? name,
268 });
269 }
270
271 return toAttrs(current, env.project, env.region);
272 }),
273
274 delete: Effect.fn(function* ({ output }) {
275 yield* transcoder
276 .deleteProjectsLocationsJobTemplates({
277 name: output.name,
278 allowMissing: true,
279 })
280 .pipe(
281 Effect.catchTag("NotFound", () => Effect.void),
282 Effect.retry({
283 while: (error) => error._tag === "Conflict",
284 times: 8,
285 schedule: Schedule.spaced("1 second"),
286 }),
287 );
288 yield* waitUntilGone(output.name);
289 }),
290 });